简体   繁体   English

SQL在多列上保留外连接

[英]SQL left outer join on multiple columns

According to this SQL join cheat-sheet , a left outer join on one column is the following : 根据此SQL连接备忘单 ,一列上的左外连接如下:

SELECT *
  FROM a
  LEFT JOIN b 
    ON a.foo = b.foo
  WHERE b.foo IS NULL 

I'm wondering what it would look like with a join on multiple columns, should it be an OR or an AND in the WHERE clause ? 我想知道在多个列上连接会是什么样子,如果它是WHERE子句中的ORAND

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL 
  OR  b.bar IS NULL 
  OR  b.ter IS NULL

or 要么

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL 
  AND b.bar IS NULL 
  AND b.ter IS NULL

?

(I don't think it does, but in case it matters, the db engine is Vertica's) (我不认为它,但如果重要,db引擎是Vertica的)

(I'm betting on the OR one) (我打赌OR一个)

That depends on whether the columns are nullable, but assuming they are not, checking any of them will do: 这取决于列是否可以为空,但假设它们不是,检查它们中的任何一个将执行:

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL -- this could also be bar or ter

This is because after a successful join, all three columns will have a non-null value. 这是因为在成功连接之后,所有三列都将具有非空值。

If some of these columns were nullable and you'd like to check if any one of them had a value after the join, then your first ( OR ) approach would be OK. 如果这些列中的某些列可以为空并且您想要检查它们中的任何一个是否在连接后具有值,那么您的第一个( OR )方法就可以了。

You can use any combination of criteria for joining: 您可以使用任何标准组合进行加入:

SELECT *
FROM a
LEFT JOIN b ON a.foo = b.foo AND a.bar = b.bar AND a.ter = b.ter

The WHERE clause has nothing to do with the join itself. WHERE子句与连接本身无关。 The WHERE b.foo IS NULL in first query will return all records from a that had no matching records in b or when b.foo was null . WHERE b.foo IS NULL在第一查询将返回所有记录, a是曾在没有符合条件的记录b或当b.foonull

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

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