0

このような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' 

私が得ている結果は
root
--Garments
--IT
----Gents Garments
----Sarees
----IT Hardware
----IT Software
------Bridal Sarees
------Webデザイン
------Web ベースのソリューション
しかし、
ルートのような結果が欲しい -- 衣服 ----紳士服 ----サリー ------ブライダル サリー
--IT ----IT ハードウェア -- --ITソフトウェア ------Webデザイン ------Webベースのソリューション








4

1 に答える 1