有關數據庫SQL遞歸查詢在分歧數據庫中的完成辦法。本站提示廣大學習愛好者:(有關數據庫SQL遞歸查詢在分歧數據庫中的完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是有關數據庫SQL遞歸查詢在分歧數據庫中的完成辦法正文
本文給年夜家引見有關數據庫SQL遞歸查詢在分歧數據庫中的完成辦法,詳細內容請看下文。
好比表構造數據以下:
Table:Tree
ID Name ParentId
1 一級 0
2 二級 1
3 三級 2
4 四級 3
SQL SERVER 2005查詢辦法:
//上查 with tmpTree as ( select * from Tree where Id=2 union all select p.* from tmpTree inner join Tree p on p.Id=tmpTree.ParentId ) select * from tmpTree //下查 with tmpTree as ( select * from Tree where Id=2 union all select s.* from tmpTree inner join Tree s on s.ParentId=tmpTree.Id ) select * from tmpTree
SQL SERVER 2008及今後版本,還可用以下辦法:
增長一列TID,類型設為:hierarchyid(這個是CLR類型,表現層級),且撤消ParentId字段,釀成以下:(表名為:Tree2)
TId Id Name
0x 1 一級
0x58 2 二級
0x5B40 3 三級
0x5B5E 4 四級
查詢辦法:
SELECT *,TId.GetLevel() as [level] FROM Tree2 --獲得一切層級 DECLARE @ParentTree hierarchyid SELECT @ParentTree=TId FROM Tree2 WHERE Id=2 SELECT *,TId.GetLevel()AS [level] FROM Tree2 WHERE TId.IsDescendantOf(@ParentTree)=1 --獲得指定的節點一切上級 DECLARE @ChildTree hierarchyid SELECT @ChildTree=TId FROM Tree2 WHERE Id=3 SELECT *,TId.GetLevel()AS [level] FROM Tree2 WHERE @ChildTree.IsDescendantOf(TId)=1 --獲得指定的節點一切下級
ORACLE中的查詢辦法:
SELECT * FROM Tree START WITH Id=2 CONNECT BY PRIOR ID=ParentId --下查 SELECT * FROM Tree START WITH Id=2 CONNECT BY ID= PRIOR ParentId --上查
MYSQL 中的查詢辦法:
//界說一個根據ID查詢一切父ID為這個指定的ID的字符串列表,以逗號分隔 CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(rootId int,direction int) RETURNS varchar(1000) CHARSET utf8 BEGIN DECLARE sTemp VARCHAR(5000); DECLARE sTempChd VARCHAR(1000); SET sTemp = '$'; IF direction=1 THEN SET sTempChd =cast(rootId as CHAR); ELSEIF direction=2 THEN SELECT cast(ParentId as CHAR) into sTempChd FROM Tree WHERE Id=rootId; END IF; WHILE sTempChd is not null DO SET sTemp = concat(sTemp,',',sTempChd); SELECT group_concat(id) INTO sTempChd FROM Tree where (direction=1 and FIND_IN_SET(ParentId,sTempChd)>0) or (direction=2 and FIND_IN_SET(Id,sTempChd)>0); END WHILE; RETURN sTemp; END //查詢辦法: select * from tree where find_in_set(id,getChildLst(1,1));--下查 select * from tree where find_in_set(id,getChildLst(1,2));--上查
彌補解釋:下面這個辦法鄙人查是沒有成績,但在上查時會湧現成績,緣由在於我的邏輯寫錯了,存在逝世輪回,現已修改,新的辦法以下:
CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(rootId int,direction int) RETURNS varchar(1000) 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
如許遞歸查詢就很便利了。