mysql中如何查询rootid为某值的所有子节点记录?
示例数据如下:
sql:
CREATE DATABASE IF NOT EXISTS `demo` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */; USE `demo`; -- Dumping structure for table demo.dic DROP TABLE IF EXISTS `dic`; CREATE TABLE IF NOT EXISTS `dic` ( `id` int(11) NOT NULL AUTO_INCREMENT, `pid` int(11) NOT NULL DEFAULT '0', `title` varchar(50) DEFAULT NULL, `data` varchar(50) DEFAULT NULL, `orderindex` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; -- Dumping data for table demo.dic: ~0 rows (approximately) /*!40000 ALTER TABLE `dic` DISABLE KEYS */; INSERT INTO `dic` (`id`, `pid`, `title`, `data`, `orderindex`) VALUES (1, 0, '一类', '111', 1), (2, 0, '二类', '222', 5), (3, 1, '一类1小类', '1-1', 6), (4, 1, '一类2小类', '1-2', 2), (5, 2, '二类1小类', '2-1', 4), (6, 4, '一类2小类1小小类', '2-1-1', 3);
自定义一个函数getChildId:
USE demo; drop function if exists getChildId; DELIMITER $$ create function getChildId(rootId varchar(20)) returns varchar (1000) DETERMINISTIC BEGIN DECLARE pTemp VARCHAR(1000); DECLARE cTemp VARCHAR(1000); -- 节点ID(临时变量) SET pTemp = '$'; SET cTemp =cast(rootId as CHAR); -- 把rootId强制转换为字符。 WHILE cTemp is not null DO SET pTemp = concat(pTemp,',',cTemp); -- 把所有节点连接成字符串。 SELECT group_concat(id) INTO cTemp FROM dic WHERE FIND_IN_SET(pid,cTemp)>0; END WHILE; RETURN pTemp; END $$ DELIMITER ;
查询示例:
SELECT * from dic WHERE find_in_set(id,getChildId(1))
查询结果:
0条评论
点击登录参与评论