mysql查询缩进子项并将所有子项分组

时间:2013-10-26 00:48:59

标签: php mysql parent-child hierarchical-data adjacency-list

我有一个像这样的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' 

我得到的结果是 根
--Garments
--IT
----男士服装 ----纱丽
---- IT硬件
---- IT软件
------新娘纱丽郎 ------网页设计
------基于Web的解决方案
但我希望结果像是 根
--Garments
----男士服装 ----纱丽
------新娘纱丽郎 --IT
---- IT硬件
---- IT软件
------网页设计
------基于Web的解决方案

1 个答案:

答案 0 :(得分:0)

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