本文主要和大家分享25行实现mysql树查询代码详解,希望能帮助到大家。
需求:查找当前(任意)级别下的所有子节点。
通过自定义mysql函数实现,先贴代码,后面给出详细说明:
delimiter $$
create function `getchildlist`(rootid int)
returns varchar(1024)
begin
declare childliststr varchar(1024);
declare tempchildstr varchar(1024);
declare rootidstr varchar(64);
set childliststr=null;
set rootidstr=cast(rootid as char);
myloop: while true
do
select group_concat(id) into tempchildstr from test where find_in_set(parrent_id,rootidstr)>0;
if tempchildstr is not null then
set rootidstr=tempchildstr;
if childliststr is null then
set childliststr=tempchildstr;
else
set childliststr=concat(childliststr,',',tempchildstr);
end if;
else
leave myloop;
end if;
end while;
return childliststr;
end $$
建表sql:
create table `test` (
`id` int(11) unsigned not null auto_increment,
`parrent_id` int(11) default '0',
`name` varchar(32) default null,
primary key (`id`)
) engine=innodb auto_increment=12 default charset=utf8;
+------------+------------------+------+-----+---------+----------------+
| field | type | null | key | default | extra |
+------------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | no | pri | null | auto_increment |
| parrent_id | int(11) | yes | | 0 | |
| name | varchar(32) | yes | | null | |
+------------+------------------+------+-----+---------+----------------+
+----+------------+------+
| id | parrent_id | name |
+----+------------+------+
| 1 | 0 | cg1 |
| 2 | 1 | cg2 |
| 3 | 2 | cg3 |
| 4 | 3 | cg4 |
| 5 | 4 | cg5 |
| 6 | 5 | cg6 |
| 7 | 6 | cg7 |
| 8 | 7 | cg8 |
| 9 | 8 | cg9 |
| 10 | 1 | cg10 |
| 11 | 2 | cg11 |
+----+------------+------+
第1行:
delimiter编写函数体内容的时候,需要使用 delimiter 关键字将分隔符先修改为别的,否则编写语句的时候写到 ';' 的时候会直接执行,导致函数编写失败
2-4行:mysql函数语法规范,不多解释
5-9行:定义逻辑所需变量。
childliststr:最终返回的子节点ids_str(例如:1,2,3,4,5)。
tempchildstr: 临时子节点ids_str(例如:1)。
rootidstr: 输入根节点转换为char类型。
10-23行: 整个函数最关键的地方在while里面对tempchildstr的处理,以及对 内置函数group_concat和find_in_set的理解
每一次循环,通过 group_concat函数找出输入的根节点的直接下级节点,通过group_concat函数得到这些子节点的id组成的字符串。并将这次得到的子字符串作为根节点,去寻找下一级的所有的子节点。
最后找到最后子节点没有下级时候,tempchildstr is not null。退出循环,返回结果。
运行结果:
mysql> select getchildlist(1);
+-----------------------+
| getchildlist(1) |
+-----------------------+
| 2,10,3,11,4,5,6,7,8,9 |
+-----------------------+
1 row in set (0.00 sec)
mysql> select getchildlist(2);
+------------------+
| getchildlist(2) |
+------------------+
| 3,11,4,5,6,7,8,9 |
+------------------+
1 row in set (0.00 sec)
相关推荐:
sql语句实现子孙树查询经典实例
mysql-使用mysql实现oracle start with connect by递归树查询
oracle树查询及相关函数
以上就是25行实现mysql树查询代码详解的详细内容。