2016-03-15 31 views
1

發現親子樹我有一個表child在那裏我有以下結構:如何從SQL表

id child_name parent_id parent_name 
1 vikas  2   sunny 
2 john   3   seema 
3 ajay   4   delhi 
4 josh   4   main 

我試圖找到孩子父母,直到PARENT_NAME匹配爲主,那麼我就會停下來。如果可能的話,我需要單個查詢sql。

我試過這個,但它只給我一個級別。

SELECT ChildUserType.child_name, 
     ChildUserType.parent_name,  
     ParentUserType.id, 
     ParentUserType.parent_id 
FROM groups AS ChildUserType 
    LEFT JOIN groups AS ParentUserType 
     ON ChildUserType.id = ParentUserType.parent_id 
where ChildUserType.id='1'; 
+0

能否請你告訴你有什麼到目前爲止已經試過?在SO,我們想幫助解決技術問題或類似問題,我們不能從頭開始提供代碼。請閱讀我們的[如何問問指南](http://stackoverflow.com/help/how-to-ask)以獲取更多詳細信息 – dubes

+0

我正在用我的答案編輯此內容。 –

+0

我想通過哪裏id = 1,然後試圖找到所有的孩子,其中id = 1。 –

回答

0

你可以試試這個:

CREATE PROCEDURE find_ancestry(IN id_init int) 
BEGIN 
DECLARE child_id int; 
DECLARE prev_id int; 
SET prev_id = id_init; 
SET child_id=0; 
SELECT parent_id into child_id 
FROM groups WHERE id=id_init ; 
create TEMPORARY table IF NOT EXISTS temp_table as (select * from groups where 1=0); 
truncate table temp_table; 
WHILE child_id <> 0 DO 
    insert into temp_table select * from groups WHERE id=prev_id; 
    SET prev_id = child_id; 
    SET child_id=0; 
    SELECT parent_id into child_id 
    FROM groups WHERE id=prev_id; 
END WHILE; 
select * from temp_table; 
END //