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

來源:互聯網
上載者:User

標籤:

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子查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.