我有一个categories
表,如下所示:
id | name | parent
-----------------------
1 | Toys | 1
2 | Clothing | 1
3 | Kid's Toys | 0
我有另一个名为category_relationships
的表,如下所示:
id | category_id | parent_id
----------------------------
1 | 3 | 1
我希望得到以下输出:
分类
Toys
- Kid's Toys
Clothing
如何通过一个查询实现这一目标?
答案 0 :(得分:0)
更好/正确/健全的答案可能会为此创建一个MySQL PROCEDURE,但如果您的数据符合这些限制,您可以使用以下内容:
此查询使用Concat构建可排序的引用,以便A的子节点在A等之后。使用concat和前导空格手动缩进名称。
select concat(1000000 + a.id, '|') SORT
,a.name
from categories a
where a.parent = 1 # top level parents only
union all
select concat(1000000 + a.id, '|',
1000000 + IFNULL(b.id,0), '|')
,concat(' - ', b.name)
from categories a
inner join category_relationships a1 on a1.parent_id = a.id
inner join categories b on b.id = a1.category_id
where a.parent = 1
union all
select concat(1000000 + a.id, '|',
1000000 + IFNULL(b.id,0), '|',
1000000 + IFNULL(c.id,0), '|')
,concat(' - ', c.name)
from categories a
inner join category_relationships a1 on a1.parent_id = a.id
inner join categories b on b.id = a1.category_id
inner join category_relationships b1 on b1.parent_id = b.id
inner join categories c on c.id = b1.category_id
where a.parent = 1
union all
select concat(1000000 + a.id, '|',
1000000 + IFNULL(b.id,0), '|',
1000000 + IFNULL(c.id,0), '|',
1000000 + IFNULL(d.id,0), '|')
,concat(' - ', d.name)
from categories a
inner join category_relationships a1 on a1.parent_id = a.id
inner join categories b on b.id = a1.category_id
inner join category_relationships b1 on b1.parent_id = b.id
inner join categories c on c.id = b1.category_id
inner join category_relationships c1 on c1.parent_id = c.id
inner join categories d on d.id = c1.category_id
where a.parent = 1
union all
select concat(1000000 + a.id, '|',
1000000 + IFNULL(b.id,0), '|',
1000000 + IFNULL(c.id,0), '|',
1000000 + IFNULL(d.id,0), '|',
1000000 + IFNULL(e.id,0))
,concat(' - ', e.name)
from categories a
inner join category_relationships a1 on a1.parent_id = a.id
inner join categories b on b.id = a1.category_id
inner join category_relationships b1 on b1.parent_id = b.id
inner join categories c on c.id = b1.category_id
inner join category_relationships c1 on c1.parent_id = c.id
inner join categories d on d.id = c1.category_id
inner join category_relationships d1 on d1.parent_id = d.id
inner join categories e on e.id = d1.category_id
order by SORT