带AND OR条件的左连接需要括在括号中

时间:2014-06-19 19:56:11

标签: sql oracle left-join

我的查询是:

select * from A left join B on a.id = b.id 
and a. id <> "N/A" and b.id <> "N/A" 
OR 
A.ID = "N/A" AND B.ID = "N/A" AND A.COL2 IS NOT NULL

基本上,只有在满足其中一个id条件时,我才想加入OR列。
这个查询是正确的还是我需要在括号中包含该部分?

a. id <> "N/A" and b.id "N/A" 
OR 
A.ID = "N/A" AND B.ID = "N/A" AND A.COL2 IS NOT NULL

1 个答案:

答案 0 :(得分:0)

AND的优先级高于OR(类似于&#34; *来自+&#34;)。

因此这个表达式:

a. id <> "N/A" AND b.id <> "N/A" 
OR 
A.ID = "N/A" AND B.ID = "N/A" AND A.COL2 IS NOT NULL

......等同于......

(a. id <> "N/A" AND b.id <> "N/A")
OR 
(A.ID = "N/A" AND B.ID = "N/A" AND A.COL2 IS NOT NULL)

但是因为a.id = b.id应该永远是真的,你必须至少放一对括号

SELECT * FROM A LEFT JOIN B ON 
  a.id = b.id AND 
  (
    a. id <> "N/A" AND b.id <> "N/A" 
    OR 
    A.ID = "N/A" AND B.ID = "N/A" AND A.COL2 IS NOT NULL
  )