java - 按代码排序

标签 java sql postgresql sorting

我在数据库中有食物类别,例如:

 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/

相关文章:

Java Bean 投影

mysql - 如何从表中查询总和(特定列值)等于输入值的结果列表

MySQL 5.6 选择月份和日期

带有自动列的 Postgresql 准备语句

sql - 使用一对一的键快速合并表

java - 序列化变量的虚拟值

java - 从 Spotify End Point 获取所需的图像

java - 如何指示 Spring Boot 在运行测试时使用测试资源中的 application.properties 文件

mysql - 帮助 SQL 连接结合大量子查询

sql - Oracle 到 Postgresql 查询转换