开发者

Problem with nested left-joins and coalesce

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开发者_JAVA百科 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!


I have translated your query to Oracle syntax and I get the expected result

+------+------+--------+
| KEY1 | KEY3 | VALUE2 |
+------+------+--------+
|    1 |    1 |      1 |
+------+------+--------+

resulting from

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

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


I got answer from postgresql team. Verdict:

This is on HEAD from today.  Clearly there's a problem.

So, it was (and it is) a bug. Thanks for all, who participated in this issue! =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜