2013-04-09 33 views
0

我在分貝等食品類:排序由代碼

category_id | parent_id | code |    name    
-------------+-----------+--------+---------------------------------- 
      1 |   |  | root 
      2 |   1 | 1  | vegetables 
      11 |   1 | 10  | seeds 
      54 |  11 | 10.1 | sunflower seeds 
      12 |   1 | 11  | sugar and candy 
      22 |   2 | 1.1 | frozen vegetables 

我想或者通過在查詢code或編程方式使用PARENT_ID(在POJO映射之後)對它進行排序。效果應該是這樣的:

1 
---1.1 
------1.1.1 
------1.1.2 
------1.1.3 
---1.2 
2 
3 
---3.1 
... 

我已經嘗試過ORDER BY code但我收到訂購記錄等:1,10.1.1,11,1.1.1 我應該嘗試將它在查詢排序或當它的映射。也許在那裏已經有接口/其他utils在這個目的?

code類型是字符改變,我使用PostgreSQL

+0

你能粘貼您的查詢?查詢shld就足夠了。還澄清「在查詢中的代碼或以編程方式使用parent_id」,你想按代碼或parentid排序嗎? – Lokesh 2013-04-09 07:36:09

+0

什麼是代碼的數據類型?字符串或數字? – Ankit 2013-04-09 07:36:18

+0

必須是一個字符串,因爲他將'1.1.1'列爲輸出之一。 – Sanchit 2013-04-09 07:39:56

回答

1

就是這樣。這由parent_id排序,因爲在你的code列這樣的varchar列上排序並不容易,因爲字符排序和數字排序不匹配。

with recursive cat_tree as (
    select category_id, parent_id, name, array[category_id] as sort, category_id::text as path 
    from category 
    where parent_id is null 
    union all 
    select c.category_id, c.parent_id, c.name, p.sort||c.category_id, p.path||'.'||c.category_id 
    from category c 
    join cat_tree p on p.category_id = c.parent_id 
) 
select category_id, parent_id, path, name 
from cat_tree 
order by sort; 

SQLFiddle:http://sqlfiddle.com/#!12/fab3c/1

+0

完美!這是我能說的:)謝謝你 – 2013-04-09 08:05:28

0

的Postgres可以做到分層/遞歸查詢,讓你可以真正把你的數據作爲樹形結構。 This tutorial對此有一個很好的解釋。事實上,這裏選擇的例子非常接近你想要做的事情。