简体   繁体   English

左联接三桌

[英]LEFT JOIN THREE tables

How to create sql query to select the distinct table A data as in the image 如何创建sql查询以选择不同的表A数据,如图所示 图片

Thanks 谢谢

One method is minus : 一种方法是minus

select . . .
from a
minus
select . . .
from b
minus
select . . .
from c;

Or, not exists : not exists

select a.*
from a
where not exists (select 1 from b where . . . ) and
      not exists (select 1 from c where . . . );

You don't clarify what the matching conditions are, so I've used . . . 您没有弄清楚匹配条件是什么,因此我使用了. . . . . . for generality. 出于普遍性。

These two versions are not the same . 这两个版本不相同 The first returns unique combinations of columns from a where those same columns are not in b or c . 从所述第一返回列的独特组合a其中那些相同列不在bc The second returns all columns from a , where another set is not in b or c . 第二返回从所有a ,其中的另一组是不是在bc

If you must use LEFT JOIN to implement what is really an anti join , then do this: 如果必须使用LEFT 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

This reads: 内容为:

  • FROM : Get all rows from a FROM :从中获取所有行
  • LEFT JOIN : Optionally get the matching rows from b and c as well LEFT JOIN :也可以选择从b和c获取匹配的行
  • WHERE : In fact, no. WHERE :其实没有。 Keep only those rows from a, for which there was no match in b and c 仅保留a和b和c中没有匹配项的那些行

Using NOT EXISTS() is a more elegant way to run an anti-join, though. 但是,使用NOT EXISTS()是运行反NOT EXISTS()一种更优雅的方法。 I tend to not recommend NOT IN() because of the delicate implications around three valued logic - which can lead to not getting any results at all . 我倾向于不建议NOT IN()因为围绕三个值逻辑的微妙含义-这可能会导致没有得到所有任何结果。

Side note on using Venn diagrams for joins 关于使用维恩图进行联接的注释

A lot of people like using Venn diagrams to illustrate joins. 许多人喜欢使用维恩图来说明联接。 I think this is a bad habit, Venn diagrams model set operations (like UNION , INTERSECT , or in your case EXCEPT / MINUS ) very well. 我认为这是个坏习惯,维恩图模型集操作 (例如UNIONINTERSECT ,或者在您的情况下为EXCEPT / MINUS )非常好。 Joins are filtered cross products, which is an entirely different kind of operation. 连接是经过筛选的叉积,这是完全不同的一种操作。 I've blogged about it here . 我在这里写过博客

Select what isn't in B nor C nor in A inner join B inner join C 选择B或C或A内联接B中不存在的内容

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) )

or also: --- you don't need a join so jou can avoid doing it 或者:---您不需要加入,因此jou可以避免这样做

select * from A
where a.id not in (select coalesce (B.ID,C.ID) AS ID from B,C)

I would do like this: 我会这样:

SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL

Someone already ask something related to your question, you should see it here 有人已经问过与您的问题有关的内容,您应该在此处查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM