MySql/Oracle树形结构查询

Oracle树形结构递归查询

在Oracle中,对于树形查询可以使start with ... connect by 

select * from treeTable start with id='1' connect by id = prior parent_id;

若将一个树状结构存储在一张表里,需要在表中存入两个字段ID和PARENTID,表示每一条记录的parent是谁。

table: treeTable

1.从根节点遍历子节点.:(一整棵树)

select * from treeTable start with id=1 connect by prior id=parentid (prior 表示上一条记录)

2.从一个叶子追溯到根节点:(树的一枝)

select * from treeTable start with id=3 connect by prior parentid=id (prior 表示上一条记录)

3.可通过level 关键字查询所在层次.

select *,level from treeTable start with id=1 connect by prior id=parentid (prior 表示上一条记录)

MySql树形结构递归查询

 mysq虽没有自带的语法支持,不过可以通过创建函数来实现递归查询。

如下图所示。。。

直接上sql语句

create table `nodelist` (
    `id` int (11),
    `nodecontent` varchar (300),
    `pid` int (11)
); 
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('1','a',NULL);
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('2','b','1');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('3','c','1');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('4','d','2');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('5','e','3');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('6','f','3');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('7','g','5');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('8','h','7');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('9','i','8');
insert into `nodelist` (`id`, `nodecontent`, `pid`) values('10','j','8');

 之后创建一个函数

DROP FUNCTION IF EXISTS `getChild`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `getChild`(rootId INT) RETURNS VARCHAR(1000) CHARSET utf8
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 nodelist   
                WHERE FIND_IN_SET(pid,ctemp)>0; 
               END WHILE;  
               RETURN ptemp;  
    END$$
DELIMITER ;

OK,查询可以通过将函数当做一个查询条件。

SELECT * FROM nodelist WHERE FIND_IN_SET(id, getChild(3))

借鉴 https://www.jianshu.com/p/f99665266bb1

里面用到的内置函数 https://baijiahao.baidu.com/s?id=1595349117525189591&wfr=spider&for=pc

posted @ 2018-12-24 09:46  zsq_fengchen  阅读(927)  评论(0编辑  收藏  举报