我在数据库中有食物类别,例如:
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
我应该尝试在查询中或在映射时对它进行排序吗?也许java中已经有用于此目的的接口(interface)/其他实用程序?
code
类型是字符变化的,我使用的是 PostgreSQL
最佳答案
类似这样的事情。它按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
关于java - 按代码排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15895948/