如何将这两个表连接在一起(MySQL,分层查询)?

时间:2011-01-23 22:22:07

标签: sql mysql hierarchical-data

我有一个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

如何通过一个查询实现这一目标?

1 个答案:

答案 0 :(得分:0)

更好/正确/健全的答案可能会为此创建一个MySQL PROCEDURE,但如果您的数据符合这些限制,您可以使用以下内容:

  • 不超过5个级别(或根据需要扩展模式)
  • ID不超过6位数(或更改连接表达式)

此查询使用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