SQL遞歸查詢在不同數據庫中的實現方法

比如表結構數據如下:

Table:Tree

ID Name ParentId

1 一級  0

2  二級  1

3  三級  2

4 四級  3

 

mysql中

//查詢方法: 表中id爲 Integer類型

select * from tree where find_in_set(id,getChildLst(1,1));--根據id查所有下級

select * from tree where find_in_set(id,getChildLst(1,2));--根據id查所有上級

CREATE  FUNCTION `getChildLst`(rootId int,direction int) RETURNS varchar(4000) CHARSET utf8
BEGIN
 DECLARE sTemp VARCHAR(5000);
   DECLARE sTempChd VARCHAR(1000);
   SET sTemp = '$';
   SET sTempChd =cast(rootId as CHAR);
    
   IF direction=1 THEN
    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(id) INTO sTempChd FROM Tree where FIND_IN_SET(ParentId,sTempChd)>0;
    END WHILE;
   ELSEIF direction=2 THEN
    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(ParentId) INTO sTempChd FROM Tree where  FIND_IN_SET(Id,sTempChd)>0;
    END WHILE;
   END IF;
 
RETURN sTemp;
END

//查詢方法: 表中id爲 String類型 36位uuid

表結構

ccms_menu_func_tree

主鍵        節點名       上級節點名

node_id  node_name  up_node_id

 

//查詢方法:
select * from ccms_menu_func_tree where find_in_set(node_id,getChildLst('id',1));--下查
select * from ccms_menu_func_tree where find_in_set(node_id,getChildLst('id',2));--上查



	
根據下級遞歸查詢上級菜單   direction 1 下查  2上查
CREATE FUNCTION getMenuChildLst(nodeId VARCHAR(36),direction int)RETURNS varchar(4000) CHARSET utf8
BEGIN
 DECLARE sTemp VARCHAR(5000);
   DECLARE sTempChd VARCHAR(1000);
   SET sTemp = '$';
   SET sTempChd =cast(nodeId as CHAR);
    
   IF direction=1 THEN
    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(node_id) INTO sTempChd FROM ccms_menu_func_tree where FIND_IN_SET(up_node_id,sTempChd)>0;
    END WHILE;
   ELSEIF direction=2 THEN
    WHILE sTempChd is not null DO
        SET sTemp = concat(sTemp,',',sTempChd);
        SELECT group_concat(up_node_id) INTO sTempChd FROM ccms_menu_func_tree where  FIND_IN_SET(node_id,sTempChd)>0;
    END WHILE;
   END IF;
 
RETURN sTemp;
END

 

 

 

ORACLE中的查詢方法:

1

2

3

4

5

6

7

8

9

SELECT *

FROM Tree

START WITH Id=2

CONNECT BY PRIOR ID=ParentId --下查

 

SELECT *

FROM Tree

START WITH Id=2

CONNECT BY ID= PRIOR  ParentId --上查

可參見相關文章:http://blog.csdn.net/super_marioli/article/details/6253639

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章