最快得到MYSQL兩個表的差集


http://www.dewen.net.cn/q/15423

 

 

Mysql里不外乎就是 子查詢 和 連接 兩種方式.

設第一個表為table1, 第二個為table2, table1包含table2.

sql為:

//子查詢
select table1.id from table1 
  where not exists 
    (select 1 from table2 
     where table1.id = table2.id
    );

//外連接
select table1.id from table1 
  left join table2
  on table1.id=table2.id
where table2.id is null;

 

 

高性能mysql里有類似的例子, 見 "When a correlated subquery is good" 一節. 它給出的數據, 外連接要快.

還有就是, 要最快, 那么最好只對 兩張表的主鍵 做差集, 這樣只過覆蓋索引, 會快一些.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM