1. 程式人生 > >MySql/Oracle樹形結構查詢

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