如何创建sql查询来选择不同的表A数据,如图所示
谢谢
发布于 2018-05-28 11:06:23
一种方法是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
中。
发布于 2018-05-28 11:08:02
如果您必须使用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
:从aLEFT JOIN
:获取所有行可选地从b和c获取匹配的行作为wellWHERE
:事实上,不是。只保留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。
发布于 2018-05-28 11:07:46
选择不在B或C或A中的内容inner join B inner join 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)
https://stackoverflow.com/questions/50564938
复制相似问题