码迷,mamicode.com
首页 > 数据库 > 详细

Mysql 递归查询

时间:2018-05-30 21:26:08      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:arc   pre   inno   _id   http   方式   rem   drop   ret   

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 递归查询

标签:arc   pre   inno   _id   http   方式   rem   drop   ret   

原文地址:https://www.cnblogs.com/keepruning/p/9112645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!