sql - 如何从类别表中以分层形式输出所有类别和子类别?

标签 sql postgresql

我有一个包含列 id、name、level、parent_id 的类别表。我有一个产品类别,例如 .. Jewellery and watches > Jewellery > Ear-rings。

我的分类看起来像

id, name, level, parent_id
1, Jewellery and watches, L1, null
2, Jewellery, L2, 1,
3, Ear-rings, L3, 2

我如何编写一个会给我以下输出的查询

id, name, displayName
1, Jewellery and watches, Jewellery and watches
2, Jewellery, Jewellery and watches > Jewellery
3, Ear-rings, Jewellery and watches > Jewellery > Ear-rings

最佳答案

使用递归查询。

with recursive top_down as (
    select id, parent_id, name, name as display_name
    from categories
    where parent_id is null
union all
    select t.id, t.parent_id, t.name, concat(display_name, ' > ', t.name)
    from categories t
    join top_down r on t.parent_id = r.id
)
select id, name, display_name
from top_down;

 id |         name          |                 display_name                  
----+-----------------------+-----------------------------------------------
  1 | Jewellery and watches | Jewellery and watches
  2 | Jewellery             | Jewellery and watches > Jewellery
  3 | Ear-rings             | Jewellery and watches > Jewellery > Ear-rings
(3 rows)

请注意,level 列基本上是多余的。

关于sql - 如何从类别表中以分层形式输出所有类别和子类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54358471/

相关文章:

mysql - 查询某个事件在给定时间发生的频率

mysql - 这种僵局怎么会发生呢?

java - 如何在JAVA jdbc中运行SQL(MYSQL)存储过程?

postgresql - 长时间运行的查询和新数据

postgresql - pg8000.core.ProgrammingError : 'could not determine data type of parameter $2'

php - 使用内部查询优化查询

mysql - 带条件和的内连接

java - Criteria API 如何编写 = ANY(?1) 表达式?

sql - 从星期一开始的下一周内获取所有生日

python - 获取 ArrayField Postgres Django 的 len