答案 0 :(得分:5)
一种方法是minus
:
select . . .
from a
minus
select . . .
from b
minus
select . . .
from c;
或者,not exists
:
select a.*
from a
where not exists (select 1 from b where . . . ) and
not exists (select 1 from c where . . . );
您没有说明匹配条件是什么,所以我使用. . .
来表示一般性。
这两个版本不一样。第一个返回来自a
的列的唯一组合,其中相同的列不在b
或c
中。第二个返回a
中的所有列,其中另一个不在b
或c
中。
答案 1 :(得分:5)
如果您必须使用LEFT JOIN
来实现真正的anti join,那么请执行以下操作:
SELECT *
FROM a
LEFT JOIN b ON b.a_id = a.a_id
LEFT JOIN c ON c.a_id = a.a_id
WHERE b.a_id IS NULL
AND c.a_id IS NULL
这是:
FROM
:从LEFT JOIN
:可选择从b和c中获取匹配的行WHERE
:事实上,没有。只保留a中的那些行,b和c 使用NOT EXISTS()
是一种更优雅的方式来运行反连接。我倾向于不推荐NOT IN()
,因为围绕三个有价值的逻辑产生了微妙的影响 - 这可能导致没有得到任何结果。
很多人喜欢使用维恩图来说明连接。我认为这是一个坏习惯,维恩图模型设置操作(如UNION
,INTERSECT
,或者在您的情况下EXCEPT
/ MINUS
)很好。 Joins are filtered cross products, which is an entirely different kind of operation. I've blogged about it here
答案 2 :(得分:1)
选择B和C中没有的内容,也不选择A内连接B内连接C
Select * from A
where A.id not in ( select coalesce(b.id,c.id) AS ID
from b full outer join c on (b.id=c.id) )
或者:---你不需要加入,所以你可以避免这样做
select * from A
where a.id not in (select coalesce (B.ID,C.ID) AS ID from B,C)
答案 3 :(得分:0)
我会这样做:
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
有人已经问过与你的问题有关的事情,你应该看到它 here