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 这个软件
本文来自博客园,作者:margo,转载请注明原文链接:https://www.cnblogs.com/ZMargo/articles/12193801.html

浙公网安备 33010602011771号