我在postgresql中使用嵌套的左连接有一个奇怪的问题...这很难解释,但很容易显示=)这里我们是:
SELECT * FROM
(
SELECT 1 as key1
) sub1
LEFT JOIN
(
SELECT sub3.key3, sub4.value2 FROM
(
SELECT 1 as key3
) sub3
LEFT JOIN
(
SELECT sub5.key5, COALESCE(sub6.value1, 1) as value2
FROM
(
SELECT 1 as key5
) sub5
LEFT JOIN
(
SELECT 1 as key6, value1
FROM
(
SELECT NULL::integer as value1
) sub7
WHERE false
) sub6 ON false
)
sub4 ON sub4.key5=sub3.key3
)
sub2 ON sub1.key1 = sub2.key3
此查询的结果:
key1;key3;value2
1;1;NULL
这就是问题 - 因为sub4中的COALESCE,value2不能为NULL(至少我认为它不能是=)) 无论如何,如果我们要改变
SELECT sub3.key3, sub4.value2 FROM
与
SELECT sub3.key3, value2 FROM
我们会得到正确的结果:
key1;key3;value2
1;1;1
我的思绪和手上有什么问题吗?还是一个bug?
提前致谢!
答案 0 :(得分:1)
我已将您的查询翻译为Oracle语法,我得到了预期的结果
+------+------+--------+
| KEY1 | KEY3 | VALUE2 |
+------+------+--------+
| 1 | 1 | 1 |
+------+------+--------+
产生的
SELECT * FROM (
SELECT 1 as key1 from dual
) sub1
LEFT JOIN (
SELECT sub3.key3, sub4.value2 FROM (
SELECT 1 as key3 from dual
) sub3
LEFT JOIN (
SELECT sub5.key5, COALESCE(sub6.value1, 1) as value2
FROM (
SELECT 1 as key5 from dual
) sub5
LEFT JOIN (
SELECT 1 as key6, value1
FROM (
SELECT cast(NULL as NUMBER(7)) as value1 from dual
) sub7
WHERE 1=0
) sub6 ON 1=0
)
sub4 ON sub4.key5 = sub3.key3
)
sub2 ON sub1.key1 = sub2.key3
另外,通过阅读这个相当奇怪的查询,我仍然认为你从Postgres得到的结果是错误的。我认为您可以安全地将此文件作为错误提交给Postgres
答案 1 :(得分:1)
我从postgresql团队得到了答案。 判决:
This is on HEAD from today. Clearly there's a problem.
所以,它是(而且是)一个错误。谢谢大家,谁参与了这个问题! =)