2012-01-23 16 views
1

在CTE選擇,我串聯固定大小的ID作爲排序關鍵字:Postgres裏,ORDER BY好像不是在遞歸CTE工作

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_id和的列表sorter柱:

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

正如你可以看到第二行是出來的地方 - 它實際上應該在最後一排。

我該如何解決這個問題?


從來沒有想過。 Postgres工作正常。服務器和客戶端之間的傳輸不能保持陣列的正確排序。

抱歉,不必要的頭部劃傷和謝謝。

回答

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 +。)

+0

是的 - 這就是我的預期。讓我多研究一下。 –

+0

當你運行你的測試用例時,語法錯誤處於或接近「x」的狀態 - 我不熟悉在SELECT語句中使用VALUES的整潔操作 –

+0

請忽略最後一條評論 - 沒有足夠的咖啡。測試結果相同。我需要更多的期待。 –