0

这不是一个重复的问题,因为上面的链接只是创建了我试图回答的相同问题

我在 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 个级别的子类别。

谢谢你的帮助

约翰

4

1 回答 1

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
于 2013-09-17T15:23:39.610 回答