Mysql 递归查询
Posted 喂,wo yang 你啊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql 递归查询相关的知识,希望对你有一定的参考价值。
扫码入群,可获取一手资料和直播课程。
mysql 递归查询
定义:父子查询: 根据父 id 查询下面所有子节点数据;子父查询: 根据子 id 查询上面所有父节点数据;
1 创建表
DROP TABLE IF EXISTS `shop`; CREATE TABLE `shop` ( `shop_id` int(11) NOT \'0\' AUTO_INCREMENT, `parent_id` int(11) DEFAULT \'0\', `name` varchar(255) DEFAULT \'0\', PRIMARY KEY (`shop_id`) ) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;
2 初始化数据:
INSERT INTO `shop` VALUES (\'1\', \'0\', \'总店\'; INSERT INTO `shop` VALUES (\'2\', \'1\', \'分店1\'; INSERT INTO `shop` VALUES (\'3\', \'1\', \'分店2\'); INSERT INTO `shop` VALUES (\'4\', \'1\', \'分店3\'); INSERT INTO `shop` VALUES (\'5\', \'1\', \'分店4\'); INSERT INTO `shop` VALUES (\'6\', \'1\', \'分店5\'); INSERT INTO `shop` VALUES (\'7\', \'1\', \'分店6\');
3 向下递归
利用find_in_set()函数和group_concat()函数实现递归查询:
DROP FUNCTION IF EXISTS queryChildrShop; CREATE FUNCTION queryChildrShop(shopid INT) RETURNS VARCHAR(4000) BEGIN DECLARE sTemp VARCHAR(4000); DECLARE sTempChd VARCHAR(4000); SET sTemp=\'\'; SET sTempChd = CAST(shopid AS CHAR); WHILE sTempChd IS NOT NULL DO SET sTemp= CONCAT(sTemp,\',\',sTempChd); SELECT GROUP_CONCAT(shop_id) INTO sTempChd FROM shop WHERE FIND_IN_SET(parent_Id,sTempChd)>0; END WHILE; RETURN sTemp; END;
4 、调用方法:
select shop_id,parent_id,name from shop where FIND_IN_SET(shop_id,queryChildShop(#{shopId}))
查询说有父节点为1的门店信息
5 向上递归
DROP FUNCTION IF EXISTS queryChildrenAreaInfo1; CREATE FUNCTION queryChildrenAreaInfo1(areaId INT) RETURNS VARCHAR(4000) BEGIN DECLARE sTemp VARCHAR(4000); DECLARE sTempChd VARCHAR(4000); SET sTemp=\'$\'; SET sTempChd = CAST(areaId AS CHAR); SET sTemp = CONCAT(sTemp,\',\',sTempChd); SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd; WHILE sTempChd <> 0 DO SET sTemp = CONCAT(sTemp,\',\',sTempChd); SELECT parentId INTO sTempChd FROM t_areainfo WHERE id = sTempChd; END WHILE; RETURN sTemp; END;
6、调用方式:
select shop_id,parent_id,name from shop where FIND_IN_SET(shop_id,queryChildrenAreaInfo1(#{shopId}))
查询id为"7"的节点的所有上级节点:
以上是关于Mysql 递归查询的主要内容,如果未能解决你的问题,请参考以下文章