在postgres中,ORDER BY似乎不适用于递归cte

时间:2012-01-23 13:56:18

标签: sql postgresql recursion common-table-expression

在cte select中,我将固定大小的id连接为排序键:

with recursive cte(
        uno_id,
        uno_tp,
        pnt_uno_id,
        status,
        title,
        content,
        sorter,
        depth ) 
as( select
        uno.uno_id,
        uno.uno_tp,
        uno.pnt_uno_id,
        uno.status,
        uno.title,
        uno.content,
        uno.uno_id::text,
        1
from    uno
where   uno.uno_id = \$1 

union all

select  uno.uno_id,
        uno.uno_tp,
        uno.pnt_uno_id,
        uno.status,
        uno.title,
        uno.content,
        cte.sorter || '-' || uno.uno_id::text,
        cte.depth + 1 AS depth
from    uno 
join    cte ON uno.pnt_uno_id = cte.uno_id
    )
select  *
from    cte
order   by sorter;

这是一个显示uno_idsorter列的列表:

1152288185909250, 1152288185909250
1158885255675908, 1152288185909250-1158885255675908
1158885255675906, 1152288185909250-1158885255675906
1158885255675907, 1152288185909250-1158885255675906-1158885255675907

正如您所看到的那样,第二行不合适 - 它实际上应该是最后一行。

我该如何解决这个问题?


永远不会。 Postgres工作正常。服务器和客户端之间的传输没有维持数组的正确排序。

抱歉不必要的头部刮伤和谢谢。

1 个答案:

答案 0 :(得分:1)

必定存在某种误解。你问题中没有的东西。
请考虑以下演示:

WITH cte (uno_id, sorter) AS (
    VALUES
      ('1158885255675908'::text, '1152288185909250-1158885255675908'::text)
     ,('1152288185909250', '1152288185909250')
     ,('1158885255675907', '1152288185909250-1158885255675906-1158885255675907')
     ,('1158885255675906', '1152288185909250-1158885255675906')
    )
SELECT  *
FROM    cte
ORDER   BY sorter;

按预期结果:

      uno_id      |                       sorter
------------------+----------------------------------------------------
 1152288185909250 | 1152288185909250
 1158885255675906 | 1152288185909250-1158885255675906
 1158885255675907 | 1152288185909250-1158885255675906-1158885255675907
 1158885255675908 | 1152288185909250-1158885255675908

此排序顺序适用于any版本的PostgreSQL。 (CTE需要v8.4 +。)