gpt4 book ai didi

jquery - 多层次Mysql语句

转载 作者:行者123 更新时间:2023-11-29 13:36:03 25 4
gpt4 key购买 nike

我有一张 table

Departments

<code>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</code>



<p>As you see, for each record I have a <em>parent</em> which CAN have it's owen <em>parent</em>. 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:</p>

<p></p>
Id         Name          Sub1          Sub2          Sub3          Sub4          Sub5     
1 Michael Store
2 Michael Store Nonfood
3 Michael Store Nonfood Clothes
4 John Store
5 Michael Store Nonfood Shoes
6 Michael Store Food
7 Michael Store Nonfood Clothes Men clothes
8 Michael Store Nonfood Clothes Men clothes Shirts
9 Michael Store Food Meat
10 John Store Food

感谢您的宝贵时间!

最佳答案

非常简单:

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

关于jquery - 多层次Mysql语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18736534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com