mysql树状结构查询及注意事项
一、说明
由于Mysql不像oracle一样支持树状查询,需要用户自行处理,本文记录了一种常见的通过自定义函数的方式进行mysql树状查询的方法,以及使用的注意事项。
二、函数
CREATE DEFINER=`root`@`localhost` FUNCTION `get_child_menus`(`in_pid` varchar(64)) RETURNS varchar(10000) CHARSET utf8mb4
BEGINdeclare ids varchar(10000) default '';declare tempids varchar(10000);set tempids = in_pid;while tempids is not null doset ids = CONCAT_WS(',',ids,tempids);select GROUP_CONCAT(id) into tempids from tbl_menu where FIND_IN_SET(pid,tempids)>0;end while;return ids;
END
三、使用
select * from tbl_menu where find_in_set(id, get_child_menus("root_menu_id_0000000"));
四、注意事项
函数使用了GROUP_CONCAT函数聚合菜单id,有可能会存在结果超长被截取的情况,可以使用如下方法处理:
SET group_concat_max_len=556809;