[英]How do I join two tables and return the values from the first that aren't in the second table?
I have two tables, the first containing the id and employee_name, and the second containing the employee_id (same as id) and some other columns. 我有两个表,第一个表包含id和employee_name,第二个表包含employee_id(与id相同)和其他一些列。 How do I join the first table with the second so that I can output all the employee ID's (and the rest of the columns) in the first table that don't appear in the second? 如何将第一个表与第二个表连接在一起,以便可以输出第一个表中没有出现的所有雇员ID(以及其余列)? The query I've gotten to is this: 我得到的查询是这样的:
select employee_id
from data2 left join data1 on data2.employee_id = data1.id
where employee_id is NULL
This outputs the correct number of rows, but there are no values in them. 这将输出正确的行数,但是其中没有任何值。 Any help is greatly appreciated! 任何帮助是极大的赞赏!
Your tables are flipped in your SQL. 您的表在SQL中被翻转。 Based on your narrative, the SQL should be: 根据您的叙述,SQL应该是:
select data1.*
from data1
left join data2 on data2.employee_id = data1.id
where data2.employee_id is NULL
You need not use join, you can simply use 'not in' clause 您无需使用连接,只需使用“ not in”子句
select id
from table1
where id not in (select employee_id from table2)
Let me know, if it works. 让我知道,是否有效。
If I understand your question correctly, you want to get the records from data1
whose values of employee_id
do not exist in the column id
in data2
. 如果我正确理解了您的问题,则想从data1
获取记录,而data2
的列id
中不存在employee_id
的值。
The way the current query is structured, you are asking for employee_id ... where employee_id is NULL
so that will only return null records. 当前查询的结构方式要求您输入employee_id ... where employee_id is NULL
这样只会返回空记录。 Instead, make a query of data1
like this: 相反,对data1
如下查询:
select * from data1 where employee_id not in (select id from data2)
This uses the subquery to find a list of id
values in data2
and then only returns records from data1
whose employee_id
does not exist in that list. 这将使用子查询在data2
查找id
值列表,然后仅从data1
返回其employee_id
不存在的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.