MYYA
2019-06-18 11:13:24
如何在MySQL中進行遞歸選擇查詢?我有一個下表:col1 | col2 | col3-----+------+-------1 | a | 55 | d | 33 | k | 76 | o | 22 | 0 | 8如果用戶搜索“1”,程序將查看col1中有“1”的值。col3“5”,則程序將繼續在col1它會有“3”col3等等。所以它會打印出來:1 | a | 55 | d | 33 | k | 7如果用戶搜索“6”,它將打印出:6 | o | 22 | 0 | 8如何構建一個SELECT查詢來做這個嗎?
3 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
CREATE PROCEDURE get_tree(IN id int) BEGIN DECLARE child_id int; DECLARE prev_id int; SET prev_id = id; SET child_id=0; SELECT col3 into child_id FROM table1 WHERE col1=id ; create TEMPORARY table IF NOT EXISTS temp_table as (select * from table1 where 1=0); truncate table temp_table; WHILE child_id <> 0 DO insert into temp_table select * from table1 WHERE col1=prev_id; SET prev_id = child_id; SET child_id=0; SELECT col3 into child_id FROM TABLE1 WHERE col1=prev_id; END WHILE; select * from temp_table; END //

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
Leftclickben的答案對我有效,但我想要一條從給定節點到樹根的路徑,而這些路徑似乎是相反的,沿著樹向下。所以,為了清晰起見,我不得不翻轉一些字段并重新命名,這對我很有用,以防這也是其他人想要的-
item | parent
-------------
1 | null
2 | 1
3 | 1
4 | 2
5 | 4
6 | 3
和
select t.item_id as item_id, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;
給予:
item | parent
-------------
6 | 3
3 | 1
1 | null
添加回答
舉報
0/150
提交
取消