gpt4 book ai didi

php - mysql查询缩进子项并对所有子项进行分组

转载 作者:行者123 更新时间:2023-11-30 01:08:41 27 4
gpt4 key购买 nike

我有一个像这样的 mysql 表

id  Category         parent
2 Garments 12
3 Gents Garments 2
4 Sarees 2
5 Bridal Sarees 4
6 IT 12
7 IT Hardware 6
8 IT Software 6
9 Web Design 8
10 Web Based Solution 8
11 E-Commerce Solution 9
12 root NULL

使用mysql查询

SELECT t1.category AS lev1, t2.category as lev2, t3.category as lev3, 
t4.category as lev4
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent = t1.id
LEFT JOIN categories AS t3 ON t3.parent = t2.id
LEFT JOIN categories AS t4 ON t4.parent = t3.id
WHERE t1.category = 'root';

我能够得到这个结果

lev1    lev2       lev3            lev4
root Garments Gents Garments NULL
root Garments Sarees Bridal Sarees
root IT IT Hardware NULL
root IT IT Software Web Design
root IT IT Software Web Based Solution

现在我找不到一种方法来获取树状结构中单列中的值。示例

root
--Garments
----Gents Garments
----Sarees
--IT
----IT Hardware
----IT Software
------Web Design
------Web Based Solution

使用以下查询修改问题:

我已经部分实现了上述结果,但是钢需要使用适当的分组以下查询

SELECT distinct t1.category AS category
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent = t1.id
LEFT JOIN categories AS t3 ON t3.parent = t2.id
LEFT JOIN categories AS t4 ON t4.parent = t3.id
WHERE t1.category = 'root'
union
SELECT distinct concat('--', t2.category) as category
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent = t1.id
LEFT JOIN categories AS t3 ON t3.parent = t2.id
LEFT JOIN categories AS t4 ON t4.parent = t3.id
WHERE t1.category = 'root'
union

SELECT distinct concat('----', t3.category) as category
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent = t1.id
LEFT JOIN categories AS t3 ON t3.parent = t2.id
LEFT JOIN categories AS t4 ON t4.parent = t3.id
WHERE t1.category = 'root'
union
SELECT distinct concat('------', t4.category) as category
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.parent = t1.id
LEFT JOIN categories AS t3 ON t3.parent = t2.id
LEFT JOIN categories AS t4 ON t4.parent = t3.id
WHERE t1.category = 'root'

我得到的结果是

--服装
--IT
----男士服装
----纱丽
----IT硬件
----IT软件
------新娘纱丽
------网页设计
------基于网络的解决方案
但我想要的结果是

--服装
----男士服装
----纱丽
------新娘纱丽
--IT
----IT硬件
----IT软件
------网页设计
------基于网络的解决方案

最佳答案

如果您可以将层次结构的表示方式更改为传递闭包表,则可以利用我过去给出的几个答案。主题是如何控制查询输出的排序,与上面描述的方式相同。

关于php - mysql查询缩进子项并对所有子项进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601585/

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