![](/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.