在SQL Server中使用JOIN排除记录

时间:2018-07-20 09:35:14

标签: sql sql-server

我有3张桌子,

表MEmployee

ID Name
1  Andy
2  Donny
3  Mark
4  John

餐篮

ID Name
1  Andy

表格正在运行

ID Name
2  Donny

我想从MEmployee中创建Soccer table,但不包括Basket table和Running。这样的结果

桌上足球

ID Name
3  Mark
4  John

我的查询不起作用:

SELECT * FROM MEmployee A
INNER JOIN Basket B On A.ID = B.ID
INNER JOIN Running C ON A.ID = C.ID
WHERE A.ID <> B.ID AND A.ID = C.ID

2 个答案:

答案 0 :(得分:2)

我们可以在此处尝试使用EXCEPT

SELECT Name FROM MEmployee
EXCEPT
SELECT Name FROM Basket
EXCEPT
SELECT Name FROM Running;

enter image description here

Demo

答案 1 :(得分:1)

您可以将NOT EXISTSCTE结合使用:

with t as (
     select id, name
     from Basket
     union all
     select id, name
     from Running
)

select e.*
from MEmployee e
where not exists (select 1 from t where t.id = e.id);