How to JOIN these 2 tables together (MySQL, Hierarchical query)?
I have a categories
table that looks like this:
id | name | parent
-----------------------
1 | Toys | 1
2 | Clothing | 1
3 | Kid's Toys | 0
I have another table called category_relationships
which looks like this:
id | category_id | parent_id
----------------------------
1 | 3 | 1
I want to have the following output:
Categories:
Toys开发者_JAVA百科
- Kid's Toys
Clothing
How to achieve this with one query?
A better/proper/robust answer will probably be create a MySQL PROCEDURE for this, but if your data can fit in these limitations, you can use the below:
- no more than 5 levels (or expand the pattern as required)
- IDs are no more than 6 digits (or change the concat expressions)
This query uses Concat to build a sortable reference so that children of A come after A etc. The names are indented manually using concat and leading spaces.
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
精彩评论