3

我有以下 2 个版本的 ANSI 兼容 SQL(更改列/表名称以保护机密数据),其中一个通过遵循正确的逻辑满足我的要求,而另一个不满足。

1)ANSI Join 1-Works

SELECT b.COLUMN_A,
  COUNT(a.COLUMN_A)
FROM TABLE1 a
RIGHT OUTER JOIN
  (SELECT COLUMN_A FROM TABLE2 WHERE COLUMN_X='TEST') b
ON  a.COLUMN_A = b.COLUMN_A
AND a.COLUMN_B in (SELECT FROM TABLE3 WHERE COLUMN_Y=5)  --WORKS
GROUP BY b.COLUMN_A

1)给出这样的输出:

COLUMN_A  COUNT(COLUMN_A)
--------------------------
A       0
B       0
C       1
D       1
E       0

2)ANSI Join 2-不起作用

SELECT b.COLUMN_A,
  COUNT(a.COLUMN_A)
FROM TABLE1 a
RIGHT OUTER JOIN
  (SELECT COLUMN_A FROM TABLE2 WHERE COLUMN_X='TEST') b
ON  a.COLUMN_A = b.COLUMN_A
WHERE
a.COLUMN_B in (SELECT FROM TABLE3 WHERE COLUMN_Y=5)      --DOESN'T WORK
GROUP BY b.COLUMN_A

3)Oracle专有的join-不起作用

SELECT b.COLUMN_A,
  COUNT(a.COLUMN_A)
FROM TABLE1 a,(SELECT COLUMN_A FROM TABLE2 WHERE COLUMN_X='TEST') b
WHERE
a.COLUMN_A(+) = b.COLUMN_A
AND a.COLUMN_B in (SELECT FROM TABLE3 WHERE COLUMN_Y=5) --DOESN'T WORK
GROUP BY b.COLUMN_A

2) & 3) 给出如下输出:

COLUMN_A  COUNT(COLUMN_A)
--------------------------
C       1
D       1

我理解 (2,ANSI) & (3,PROPRIETARY) 是等价的。但是(1,ANSI)是否有任何等效的专有SQL?。任何帮助都将受到欢迎。谢谢。编辑:我已经用示例输出更新了问题。

4

1 回答 1

6

您可能想要更改此条件:

AND a.COLUMN_B in (SELECT FROM TABLE3 WHERE COLUMN_Y=5)

对此:

AND a.COLUMN_B (+) in (SELECT FROM TABLE3 WHERE COLUMN_Y=5)

或这个:

AND (a.COLUMN_B IS NULL OR a.COLUMN_B in (SELECT FROM TABLE3 WHERE COLUMN_Y=5))

但总的来说,我会说使用 ANSI 语法进行外连接。即使是第一次学习 Oracle 语法并且对它非常熟悉的人,ANSI 对于外部连接也更加清晰。

于 2011-04-29T15:06:22.673 回答