嵌套左连接和合并的问题
我在 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
这就是问题 - value2 不能为 NULL 因为 COALESCE在sub4中(至少我认为不可能=)) 无论如何,如果我们改变
SELECT sub3.key3, sub4.value2 FROM
的话,
SELECT sub3.key3, value2 FROM
我们会得到正确的结果:
key1;key3;value2
1;1;1
我的思想和手有问题吗?或者这是一个错误?
提前致谢!
I have strange issue with nested left-joins in postgresql... It's hard to explain, but easy to show =) here we are:
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
The result of this query:
key1;key3;value2
1;1;NULL
And this is the problem - value2 can't be NULL because of COALESCE in sub4 (at least I think that it can't be =))
Anyway if we'll change
SELECT sub3.key3, sub4.value2 FROM
with
SELECT sub3.key3, value2 FROM
we will got correct result:
key1;key3;value2
1;1;1
Is there something wrong with my mind&hands? or is it a bug?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我已将您的查询转换为 Oracle 语法,并且得到了预期的结果
另外
,通过阅读这个相当奇怪的查询,我仍然认为您从 Postgres 获得的结果是错误的。我认为您可以安全地将其作为错误提交给 Postgres
I have translated your query to Oracle syntax and I get the expected result
resulting from
Also, from reading this rather odd query, I still think that the result you get from Postgres is wrong. I think you can safely file this as a bug to Postgres
我从 postgresql 团队得到了答案。
结论:
所以,这是(而且确实是)一个错误。感谢所有参与本期的人! =)
I got answer from postgresql team.
Verdict:
So, it was (and it is) a bug. Thanks for all, who participated in this issue! =)