找出存在於一張表而又不存在於另外一種表的記錄

2021-06-04 19:04:07 字數 1156 閱讀 4058

表結構:

表aid name remark

1 a 58

2 b 52

3 c 23

4 c 44

5 d 24

6 d 45

表bid name 

1 a  

2 b

方法一:
--查詢語句

select id,name from a

except

select id,name from b

--結果

id name

----------- --------------------

3 c

4 d

5 e

6 f

(4 行受影響) --ms sql

方法二:

--查詢語句

select * from a

where not exists( select 1 from b where a.id=b.id)

--結果

id name

----------- --------------------

3 c

4 d

5 e

6 f

(4 行受影響)

方法三:
--查詢語句

select a.* from a

left join b on a.id = b.id

where b.id is null

--結果

id name

----------- --------------------

3 c

4 d

5 e

6 f

(4 行受影響)

選擇不存在於另一表的資料幾種寫法

選擇不存在於另一表的資料幾種寫法 看看以下三種寫法 寫法1 select from a where a.key not in select key from b 寫法2 select from a left join b on a.key b.key where b.key is null 寫法3 ...

MySQL如果不存在乙個表則建立

一 問題起因 在前幾天從同事那裡拿來demo研究的時候,發現資料庫名,部分表都一樣,只是有的表沒有,這時如果需要把兩個人的資料庫和成乙個資料庫,就需要處理判斷一張表不存在,如存在則不改動,若不存在,則執行建立。在同事那裡拿到這個資料庫的轉存檔案,然後去手動改動這個.sql轉存檔案對一些自己不確定自己...

查詢乙個表中存在而另乙個表中不存在的記錄

例如 兩個表 t1,t2 查詢在表t1中存在,而在表t2中不存在的記錄。假設以id欄位為關聯字段。方法1 需要兩個表的字段完全一致 select from t1 minus selecct from t2 方法2 select from t1 where not exists select 1 fr...