SQL JOIN中的AND / OR语句

时间:2015-07-14 13:07:18

标签: sql postgresql

我有两个表:table1table2。我可以使用id1id2加入他们。我更喜欢使用id1,但由于缺少某些行id1,因此我必须使用id2。以下语法是否正确:

SELECT *
FROM table1 as a

LEFT JOIN table2 as b
ON (a.id1 is not null and a.id1 = b.id1) or
   (a.id2 is not null and a.id2 = b.id2)

它返回一些结果,但我想确定它是否有效,因为我之前没有看过它。

有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

看起来你在评论中有一个不错的答案,但是为了将另一种可能性放入环中,你可以运行两个查询并将它们联合起来。

select * 
from table1 as a
  LEFT JOIN table2 as b
    on a.id1 = b.id1
union
select * 
from table1 as a
  LEFT JOIN table2 as b
    on a.id2 = b.id2

联合将消除集合之间的任何重复,并将返回任一条件为真的记录,就像您的或语句一样。性能方面,联合可能会慢一点,但可以让您更轻松地控制集合。例如,如果您只希望set 2在id1为null时返回结果,则只需将其添加到where子句即可。无论如何希望有所帮助。