mysql与orcale实现递归查询

时间:2022-09-19 11:21:52

一、Orcale实现递归查询

       oracle提供的connect by来实现

[sql] view plaincopy
  1. SELECT id, parentid  
  2. FROM t  
  3. CONNECT BY id = PRIOR parentid  
  4. START WITH id = '1'

  1. PRIOR在parentid前面表示向下递归,在id前面向上递归
  2. 也就是parentid PRIOR前id在后向上递归查询,id在PRIORparentid 在后向下递归查询


二、mysql实现递归查询

          mysql没有提供递归查询的语法,只能自己写一个递归查询的函数

          下面是我自己写的一个mysql例子,有兴趣可以自己执行看看效果

例:

1、创建表结构

CREATE TABLE `treenodes` (
  `id` int(11) NOT NULL,
  `nodename` varchar(20) DEFAULT NULL,
  `pid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

备注:pid为id的上节点,nodename为名称,id为主键


2、执行插入语句
INSERT INTO `treenodes` VALUES ('1', 'A', '0');
INSERT INTO `treenodes` VALUES ('2', 'B', '1');
INSERT INTO `treenodes` VALUES ('3', 'C', '1');
INSERT INTO `treenodes` VALUES ('4', 'D', '2');
INSERT INTO `treenodes` VALUES ('5', 'E', '2');
INSERT INTO `treenodes` VALUES ('6', 'F', '3');
INSERT INTO `treenodes` VALUES ('7', 'G', '6');
INSERT INTO `treenodes` VALUES ('8', 'H', '0');
INSERT INTO `treenodes` VALUES ('9', 'I', '8');
INSERT INTO `treenodes` VALUES ('10', 'J', '8');
INSERT INTO `treenodes` VALUES ('11', 'K', '8');
INSERT INTO `treenodes` VALUES ('12', 'L', '9');
INSERT INTO `treenodes` VALUES ('13', 'M', '9');
INSERT INTO `treenodes` VALUES ('14', 'N', '12');
INSERT INTO `treenodes` VALUES ('15', 'O', '12');
INSERT INTO `treenodes` VALUES ('16', 'P', '15');
INSERT INTO `treenodes` VALUES ('17', 'Q', '15');


3、执行递归函数

CREATE FUNCTION `getChildList`(rootId INT)
RETURNS varchar(1000)
BEGIN
    DECLARE sTemp VARCHAR(1000);
    DECLARE sTempChd VARCHAR(1000);

    SET sTemp = '$';
    SET sTempChd =cast(rootId as CHAR);

    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(id) INTO sTempChd FROM  treeNodes where FIND_IN_SET(pid,sTempChd)>0;
       END WHILE;
    RETURN sTemp;
END

备注:rootId 为执行函数的参数,该函数通过while循环不断向下递归查询,直到查询出为null就结束函数执行,递归向上查询只需要把pid与id互换位置就行


4、递归向下查询id为12的所有节点

select * from treenodes where FIND_IN_SET(id,getChildList(12));