如何在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
提交
取消