mysql 子查詢最佳化

來源:互聯網
上載者:User

標籤:

今天用到要查詢七天內都沒有裝機的門店資訊,首先想到了用not in,先把裝機的userid查出來,然後再id not in,但是這樣就必須使用子查詢,資料量少還可以,資料量大了的話,肯定效率特別低,因為MySQL需要為內層查詢語句的查詢結果建立一個暫存資料表。然後外層查詢語句再暫存資料表中查詢記錄。查詢完畢後,MySQL需要撤銷這些暫存資料表。因此,子查詢的速度會受到一定的影響。如果查詢的資料量比較大,這種影響就會隨之增大。

 

首先使用:

select * from v9_wba_account where levels = 3 and id not in(select distinct userid from v9_wba_dev where days > 20150917)

 

然後嘗試:

select * from v9_wba_account as user left join v9_wba_dev as dev on user.id=dev.userid where levels = 3

由於 LEFT JOIN 即使不滿足 user.id=dev.userid 這個條件,也會把左表中的資料都查詢出來,但是結果中 右表中的欄位都是NULL而已

 

最後:

select * from v9_wba_account as user left join v9_wba_dev as dev on user.id=dev.userid where levels = 3 and dev.id is NULL

最後再排除下右表不為 null 的就是正確的了

 

select * from v9_wba_account as user left join v9_wba_dev as dev on user.id=dev.userid and dev.days >= 20150918 where levels = 3  and dev.id is NULL;

ON 後面是右表的查詢條件

mysql 子查詢最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.