![](/img/trans.png)
[英]How do I join two tables and only take values from the second table if they exist?
[英]How do I join two tables and return the values from the first that aren't in the second table?
我有兩個表,第一個表包含id和employee_name,第二個表包含employee_id(與id相同)和其他一些列。 如何將第一個表與第二個表連接在一起,以便可以輸出第一個表中沒有出現的所有雇員ID(以及其余列)? 我得到的查詢是這樣的:
select employee_id
from data2 left join data1 on data2.employee_id = data1.id
where employee_id is NULL
這將輸出正確的行數,但是其中沒有任何值。 任何幫助是極大的贊賞!
您的表在SQL中被翻轉。 根據您的敘述,SQL應該是:
select data1.*
from data1
left join data2 on data2.employee_id = data1.id
where data2.employee_id is NULL
您無需使用連接,只需使用“ not in”子句
select id
from table1
where id not in (select employee_id from table2)
讓我知道,是否有效。
如果我正確理解了您的問題,則想從data1
獲取記錄,而data2
的列id
中不存在employee_id
的值。
當前查詢的結構方式要求您輸入employee_id ... where employee_id is NULL
這樣只會返回空記錄。 相反,對data1
如下查詢:
select * from data1 where employee_id not in (select id from data2)
這將使用子查詢在data2
查找id
值列表,然后僅從data1
返回其employee_id
不存在的記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.