MySql/Oracle樹形結構查詢

Oracle樹形結構遞歸查詢node

在Oracle中,對於樹形查詢可使start with ... connect by sql

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

若將一個樹狀結構存儲在一張表裏,須要在表中存入兩個字段ID和PARENTID,表示每一條記錄的parent是誰。ide

table: treeTable函數

1.從根節點遍歷子節點.:(一整棵樹)spa

select * from treeTable start with id=1 connect by prior id=parentid (prior 表示上一條記錄)code

2.從一個葉子追溯到根節點:(樹的一枝)blog

select * from treeTable start with id=3 connect by prior parentid=id (prior 表示上一條記錄)遞歸

3.可經過level 關鍵字查詢所在層次.get

select *,level from treeTable start with id=1 connect by prior id=parentid (prior 表示上一條記錄)

it

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

相關文章
相關標籤/搜索