mysql 层级查询

id name p_id  
1 jack 0  
2 rose 1  
3 tom 2  
4 jerry 1  
5 ed 3  

 

有上面这样一个表格,p_id 是父id,这里需求比如: 如果我想查出id=5 的最后的父id ,也就是id=1的p_id属性值0;

这里使用的存储过程:

CREATE DEFINER = 'root'@'%'
FUNCTION testingplatform_dev.queryParentId(c int)
  RETURNS int(11)
begin
-- select * from student;
  declare st int;
	declare stc int;
	set st = c;
	set stc = c;
	while st is not null do
	  select p_id into stc from test_group where id=stc;
	  select max(id) into st from test_group where id=stc;
	end while;
return stc;
end

需要注意的是  select max(id) into st from test_group where id=stc;  这里使用的max(id),如果根据id查询 没有这条记录,在mysql中返回的是N/A  并不是NULL,所以这里使用聚合函数稍微转下。

 


 

mysql存储过程调试使用  dbForge Studio for MySQL  这个软件

posted @ 2020-01-14 19:54  margo  阅读(603)  评论(0)    收藏  举报