簡體   English   中英

MySQL:選擇兩個表之間不通用的數據

[英]MySQL: selecting data not in common between two tables

我有3個數字的table1和1個數字的table2:

table1       table2
n              n
1              1
2
3

我想從表1中選擇表2中不存在的數據(數字2和3)。 我試過了:

select table1.* from table1, table2 where table1.n <> table2.n

我還嘗試了其他where子句:

where table1.n not like table2.n
where not table1.n = table2.n

但是我沒有得到結果。 我知道可以通過多個步驟來完成,但是我想知道是否有一個簡單的查詢可以做到。 謝謝

您需要執行LEFT JOIN並查找t2的空值。 像這樣:

SELECT
   t1.n
FROM
   table1 AS t1
   LEFT JOIN table2 AS t2
     ON t1.n = t2.n
WHERE
    t2.n IS NULL

這是指向各種JOINS的出色參考的鏈接,其中包括Venn圖,以幫助您可視化不同的聯接方法。

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

您可以使用NOT IN或NOT EXISTS來做到這一點。

select * from table1
where table1.n not in (select table2.n from table2);

select * from table1
where  not exists (select table2.n from table2 where table2.n = table1.n);

我多次嘗試了兩種方法(左聯接而不是左聯接),並且花了完全相同的時間(我的桌子很大)。 多謝你們!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM