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后面的變量就是我們使用的索引)不同擺了,我們可以對大表使用索引提高搜索速度。