SQL创建类别路径/树/层次结构

时间:2013-09-17 12:33:24

标签: mysql sql categories

这不是一个重复的问题,因为上述链接只会产生我想要回答的同样问题

我在phpmyadmin中有一个简单的表,包含类别ID,类别名称及其父类别ID,因此列标记为:id,name,parentid

示例数据:

id  name    parentid
1   animal  NULL
2   vegetable   NULL
3   mineral NULL
4   doggie  1
5   kittie  1
6   horsie  1
7   gerbil  1
8   birdie  1
9   carrot  2
10  tomato  2
11  potato  2
12  celery  2
13  rutabaga    2
14  quartz  3
15  feldspar    3
16  silica  3
17  gypsum  3
18  hunting 4
19  companion   4
20  herding 4
21  setter  18
22  pointer 18
23  terrier 18
24  poodle  19
25  chihuahua   19
26  shepherd    20
27  collie  20

我想输出所有类别路径和每个路径的ID。到目前为止,我可以使用以下sql创建路径:

select root.name  as root_name
     , down1.name as down1_name
     , down2.name as down2_name
     , down3.name as down3_name
  from categories as root
left outer
  join categories as down1
    on down1.parentid = root.id
left outer
  join categories as down2
    on down2.parentid = down1.id
left outer
  join categories as down3
    on down3.parentid = down2.id
 where root.parentid is null
order 
    by root_name 
     , down1_name 
     , down2_name 
     , down3_name

我想要添加到输出中的是每个类别的ID及其路径。我在上面找到了上述代码:http://sqllessons.com/categories.html

上面的代码创建了以下内容:

root_name   down1_name  down2_name  down3_name
animal  birdie  NULL    NULL
animal  doggie  companion   chihuahua
animal  doggie  companion   poodle
animal  doggie  herding collie
animal  doggie  herding shepherd
animal  doggie  hunting pointer
animal  doggie  hunting setter
animal  doggie  hunting terrier
animal  gerbil  NULL    NULL
animal  horsie  NULL    NULL
animal  kittie  NULL    NULL
mineral feldspar    NULL    NULL
mineral gypsum  NULL    NULL
mineral quartz  NULL    NULL
mineral silica  NULL    NULL
vegetable   carrot  NULL    NULL
vegetable   celery  NULL    NULL
vegetable   potato  NULL    NULL
vegetable   rutabaga    NULL    NULL
vegetable   tomato  NULL    NULL

但是,我希望它创建以下内容:

id  root_name   down1_name  down2_name  down3_name
8   animal  birdie  NULL    NULL
25  animal  doggie  companion   chihuahua
24  animal  doggie  companion   poodle
27  animal  doggie  herding collie
26  animal  doggie  herding shepherd
22  animal  doggie  hunting pointer
21  animal  doggie  hunting setter
23  animal  doggie  hunting terrier
7   animal  gerbil  NULL    NULL
6   animal  horsie  NULL    NULL
5   animal  kittie  NULL    NULL
15  mineral feldspar    NULL    NULL
17  mineral gypsum  NULL    NULL
14  mineral quartz  NULL    NULL
16  mineral silica  NULL    NULL
9   vegetable   carrot  NULL    NULL
12  vegetable   celery  NULL    NULL
11  vegetable   potato  NULL    NULL
13  vegetable   rutabaga    NULL    NULL
10  vegetable   tomato  NULL    NULL

请注意,上述内容来自上述链接,而真实数据可能包含最多6个级别的子类别。

感谢您的帮助

约翰

1 个答案:

答案 0 :(得分:1)

select coalesce(down3.Id, down2.Id, down1.Id, root.Id), root.name  as root_name
 , down1.name as down1_name
 , down2.name as down2_name
 , down3.name as down3_name