使用MYSQL实现Oracle的Start with…Connect By递归树查询:
准备建表SQL
DROP TABLE IF EXISTS `tb_dict_category_config`;
CREATE TABLE `tb_dict_category_config` (
`id` varchar(100) DEFAULT NULL,
`pid` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`isparent` varchar(6) DEFAULT 'false'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_dict_category_config
-- ----------------------------
INSERT INTO `tb_dict_category_config` VALUES ('103', '12', '分类60', 'false');
INSERT INTO `tb_dict_category_config` VALUES ('1', '0', '全部分类', 'true');
INSERT INTO `tb_dict_category_config` VALUES ('12', '1', '分类6', 'true');
下面是原博主提供的SQL:
CREATE FUNCTION `getChildList`(rootId INT) //rootId为你要查询的节点。
RETURNS VARCHAR(1000)
BEGIN
DECLARE pTemp VARCHAR(1000);
DECLARE cTemp VARCHAR(1000); //两个临时变量
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 nodelist
WHERE FIND_IN_SET(pid,cTemp)>0;
// FIND_IN_SET(str,strlist)的方法网上大把不解释。
END WHILE;
RETURN pTemp;
END
我根据自己的需求修改为下面的SQL:
CREATE FUNCTION `getChildList`(rootId INT)
RETURNS VARCHAR(1000)
BEGIN
DECLARE pTemp VARCHAR(1000);
DECLARE cTemp VARCHAR(1000);
SET pTemp = '$';
SET cTemp =cast(rootId as CHAR);
WHILE cTemp is not null DO
SET pTemp = concat(pTemp,',',cTemp);
SELECT group_concat(id) INTO cTemp FROM tb_dict_category_config
WHERE FIND_IN_SET(pid,cTemp)>0;
END WHILE;
RETURN pTemp;
END
执行结果:
select * from tb_dict_category_config WHERE FIND_IN_SET(id, getChildList(1));
如下图:
参考:
- http://51wifygoo1go.blog.51cto.com/6455479/1122729;