[英]How to JOIN these 2 tables together (MySQL, Hierarchical query)?
我有一個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
如何通過一個查詢實現這一目標?
一個更好/更合適/更可靠的答案可能是為此創建一個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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.