3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
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貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
Leftclickben的答案對(duì)我有效,但我想要一條從給定節(jié)點(diǎn)到樹根的路徑,而這些路徑似乎是相反的,沿著樹向下。所以,為了清晰起見,我不得不翻轉(zhuǎn)一些字段并重新命名,這對(duì)我很有用,以防這也是其他人想要的-
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
添加回答
舉報(bào)