2015-01-02 18 views
0

我有一個表3列,如:獲取父> child1_1> child1_1_1> child1_1_1_1結構僅從查詢

name | id | parent_id 

XYZ | 1 | 2 
ZYX | 3 | 1 
YXZ | 4 | 3 

難道不可能性,只是從MySQL查詢檢索可以簡單地理解爲結果字符串,如「父級> child1_1> child1_1_1> child1_1_1_1」等等?層次結構樹的最大深度爲4,「父」具有parent_id = 0。它讓我很頭疼,在PHP中構建它。

更具體地說,父類別有多個孩子,其中也有多個孩子...我想獲得所有記錄,如「計算機>網絡>路由器」,「計算機>網絡>交換機」等結果。

非常感謝!

回答

2

通常這是使用遞歸CTE的完成,MySQL不支持它

當你的深度只有4個級別,你可以使用self left join父母連像下面

concat_ws用來連接的名。

更新的答案,讓孩子最深的ID,這需要使用​​3210

select coalesce(t3.id,t2.id, t1.id) as deepChildId, 
     concat_ws('->', t.name ,t1.name, t2.name, t3.name) as childList 
from Table1 t 
left join Table1 t1 
on t.id = t1.parent_id 
left join Table1 t2 
on t1.id = t2.parent_id 
left join Table1 t3 
on t2.id = t3.parent_id 
where t.parent_id =0 
+0

輝煌!它的作用像一個魅力,但現在我有另一個問題,我不知道如何管理它。我需要具有最深類別(孩子)ID的另一列。如果我只是「SELECT t.id,concat_ws [...]」我得到父母的ID。 – valicu2000

+0

@ valicu2000,更新了這個答案,你可以使用'coalesce' – radar

+0

你真令人驚歎!非常感謝你! – valicu2000