mysql使用函数递归查找父级或子级id

   数据库    数据库  mysql

mysql使用函数递归查找父级或子级id

父级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CREATE FUNCTION `getParentList`(rootId bigint)
RETURNS varchar(1000)
BEGIN
DECLARE fid varchar(100) default '';
DECLARE str varchar(1000) default rootId;
WHILE rootId is not null do
SET fid = (SELECT parent_id FROM table_name WHERE id = rootId);
IF fid is not null AND fid > 0 THEN SET str = concat(str, ',', fid);
SET rootId = fid;
ELSE
SET rootId = fid;
END IF;
END WHILE;
RETURN str;
END

子级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
CREATE FUNCTION `getChildList`(rootId bigint) 
RETURNS VARCHAR(1000)
BEGIN
DECLARE str VARCHAR(1000);
DECLARE cid VARCHAR(1000);
DECLARE k INT DEFAULT 0;
SET cid = CAST(rootId AS CHAR);
SET str = cid;
WHILE cid IS NOT NULL DO
IF k > 0 THEN SET str = CONCAT(str, ',', cid);
END IF;
SELECT GROUP_CONCAT(id) INTO cid FROM table_name WHERE FIND_IN_SET(parent_id, cid) > 0;
SET k = k + 1;
END WHILE;
RETURN str;
END

Mysql创建测试数据

表结构

1
2
3
4
5
6
7
CREATE TABLE `test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`t_id` bigint(20) DEFAULT NULL,
`t_no` varchar(20) DEFAULT NULL,
`t_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4

存储过程

1
2
3
4
5
6
7
8
CREATE PROCEDURE create_test_data(size bigint)
BEGIN
SET @i=1;
WHILE @i<=size DO
INSERT INTO test (t_id, t_no, t_time) VALUES(concat('100', @i%3), @i%3, now());
SET @i=@i+1;
END WHILE;
END

执行存储过程

1
call create_test_data(10000)
  1. mysql使用函数递归查找父级或子级id
    1. 父级
    2. 子级
  2. Mysql创建测试数据
    1. 表结构
    2. 存储过程
    3. 执行存储过程
将hexo源文件备份到github
xxl job