我有一个包含列 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/