转换Oracle sql语法

时间:2018-05-17 12:36:56

标签: sql oracle

我想更改Oracl SQL查询的语法,

原始查询包含联接:

WHERE (A.ID = B.ID OR A.ID is null)

我想将其更改为LEFT OUTER JOININNER JOIN语法,

我尝试了以下操作,但查询没有返回相同的结果:

LEFT OUTER JOIN TABLEA A ON A.ID = B.ID

1 个答案:

答案 0 :(得分:1)

作为一个局外人,我无法肯定地说,但我强烈怀疑那个写作的人

WHERE (A.ID = B.ID OR A.ID is null)

试图进行外部联接并且完全错了。该条件在逻辑上不等同于外连接。

考虑:

with a ( id, val ) as ( 
SELECT 1, 'a one' FROM DUAL UNION ALL
SELECT 2, 'a two' FROM DUAL UNION ALL
SELECT 3, 'a three' FROM DUAL UNION ALL
SELECT null, 'a null' FROM DUAL ),
b ( id, val ) as ( 
SELECT 2, 'b two' FROM DUAL UNION ALL
SELECT 3, 'b three' FROM DUAL UNION ALL
SELECT 4, 'b four' FROM DUAL UNION ALL
SELECT null, 'a null' FROM DUAL )
select a.id aid, a.val aval, b.id bid, b.val bval
from a, b
where ( a.id = b.id or a.id is null )

+-----+---------+-----+---------+
| AID |  AVAL   | BID |  BVAL   |
+-----+---------+-----+---------+
|   2 | a two   |   2 | b two   |
|   3 | a three |   3 | b three |
|     | a null  |   2 | b two   |
|     | a null  |   3 | b three |
|     | a null  |   4 | b four  |
|     | a null  |     | a null  |
+-----+---------+-----+---------+

...您可以看到a.id的空值已加入表b中的每个行。如果表a中没有带有空id的行,则没有行具有b.id = 4(仅返回上面的前两个记录)。

相同数据的外部联接应如下所示:

select a.id aid, a.val aval, b.id bid, b.val bval from b left join a
on a.id = b.id order by a.id, b.id

+-----+---------+-----+---------+
| AID |  AVAL   | BID |  BVAL   |
+-----+---------+-----+---------+
|   2 | a two   |   2 | b two   |
|   3 | a three |   3 | b three |
|     |         |   4 | b four  |
|     |         |     | a null  |
+-----+---------+-----+---------+

我的建议:了解查询所谓的要执行的操作。如果查询的要求是外连接,请将查询修复为外连接并忽略它以前的操作 - 这是错误的。