多层次的Mysql语句

时间:2013-09-11 08:45:22

标签: jquery mysql hierarchy

我有一张桌子

Departments

Id                   Name               Parent
1                    Michael Store        0
2                    Nonfood              1
3                    Clothes              2
4                    John Store           0
5                    Shoes                2
6                    Food                 1
7                    Men clothes          3
8                    Shirts               7
9                    Meat                 6
10                   Food                 4

Id Name Parent 1 Michael Store 0 2 Nonfood 1 3 Clothes 2 4 John Store 0 5 Shoes 2 6 Food 1 7 Men clothes 3 8 Shirts 7 9 Meat 6 10 Food 4


As you see, for each record I have a parent which CAN have it's owen parent. The number of subdivisions is limited to 5. For item 8 (Shirts), you get it's parent (7) which mean that Shirts is part of item with id=7 (Men clothes), part of item with id=3 (Clothes), part of item id=2 (Nonfood), part of id=1 (Michael Store). I need a Mysql statement with the folowing result:

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

非常简单:

SELECT
  d1.id,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Name,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name)+1, d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Sub1,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name)+2, d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Sub2,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name)+3, d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Sub3,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name)+4, d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Sub4,
  ELT(FIELD(COALESCE(d6.name, d5.name, d4.name, d3.name, d2.name, d1.name), d6.name, d5.name, d4.name, d3.name, d2.name, d1.name)+5, d6.name, d5.name, d4.name, d3.name, d2.name, d1.name) AS Sub5
FROM department d1
LEFT JOIN department d2 ON d2.id = d1.parent
LEFT JOIN department d3 ON d3.id = d2.parent
LEFT JOIN department d4 ON d4.id = d3.parent
LEFT JOIN department d5 ON d5.id = d4.parent
LEFT JOIN department d6 ON d6.id = d5.parent

看到它的实际效果: http://sqlfiddle.com/#!2/303a5/20