码迷,mamicode.com
首页 > 数据库 > 详细

mysql---where子查询、form子查询、exists子查询

时间:2015-03-03 22:01:18      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

1.什么是子查询?

当一个查询是另一个查询的条件时,称之为子查询。

2.子查询有什么好处?

子查询可以使用几个简单命令构造功能强大的复合命令。

那么,现在让我们一起来学习子查询。

3.where型的子查询

给它个定义吧:where型的子查询就是把内层查询的结果当作外层查询的条件。

现在,我们来查询文章表里每组主题分类下评论最多的文章。

给定表如下:

create table article(
article_id int(3),
article_title varchar(50),
article_content text,
article_comments int(3),
articlecategory_id int(3)
);
insert into article values(1,"fff1","contteee",55,1);
insert into article values(2,"fff2","conttffffffeee",15,2);
insert into article values(3,"fff3","conttdgfdfdsfeee",515,1);
insert into article values(4,"fff4","conttesdfsdfsee",505,1);
insert into article values(5,"fff5","conttesdfsdfee",545,2);
insert into article values(6,"fff6","conttesdfsee",575,2);
insert into article values(7,"fff7","conttesdfsdee",5,1);
insert into article values(8,"fff8","conttesdfsdfee",77,1);

如:select article_id,article_title,article_content from article where article_comments in (select max(article_comments) from article group by articlecategory_id);

4.from子查询

定义:from子查询就是把子查询的结果(内存里的一张表)当作一张临时表,然后再对它进行处理。

from子查询解决上面问题

如:select tmp.article_id,tmp.article_content,article_comments from ( select * from article order by articlecategory_id,article_comments desc ) as tmp group by tmp.articlecategory_id;

5.exists子查询

定义:exists子查询就是对外层表进行循环,再对内表进行内层查询。和in ()差不多,但是它们还是有区别的。主要是看两个张表大小差的程度。

若子查询表大则用exists(内层索引),子查询表小则用in(外层索引);

效率的区别就在于使用的索引(where后面的变量就是我们使用的索引)不同摆了,我们可以对大表使用索引提高搜索速度。

mysql---where子查询、form子查询、exists子查询

标签:

原文地址:http://www.cnblogs.com/a757956132/p/4311915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!