mysql 查兩個表之間的數據差集


需要查兩個表之間的差集

首先,想到的是主鍵直接not in

select mailbox_id from co_user where mailbox_id not in (select mailbox_id from core_mailbox);

 

好吧!這個是可以,但是數據多了的話,想到這個查詢的邏輯有點受不住

於是再改為下面的這樣:

select cu.mailbox_id,cm.mailbox_id from co_user as cu 
    left join core_mailbox as cm
      on cu.mailbox_id = cm.mailbox_id
        where cm.mailbox_id is NULL;

利用了left join的,然后進行對比,並且利用where進行篩選。

后面也在網上找了這條:

SELECT mailbox_id FROM `co_user` left join 
(select mailbox_id as i from core_mailbox) as t1
on co_user.mailbox_id= t1.i where t1.i is NULL;

概念上與第二條同理。

 

好吧! 回顧了一下left join

SQL LEFT JOIN 關鍵字

LEFT JOIN 關鍵字會從左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中沒有匹配的行。

 


免責聲明!

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



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