oracle递归查询语句(oracle递归查询函数)
众所周知,目前的mysql版本中并不支持直接的递归查询,但是通过递归到迭代转化的思路,还是可以在一句SQL内实现树的递归查询的。这个得益于Mysql允许在SQL语句内使用@变量。以下是示例代码。
创建表格
CREATE TABLE `lf_ctrl_trade` ( `TRADEID` int , -- 节点ID `nodename` varchar (60), -- 节点名称 `PARENTID` int -- 节点父ID);
方案一:
SELECT TRADEID AS ID,PARENTID AS 父ID ,levels AS 父到子之间级数, paths AS 父到子路径 FROM ( SELECT TRADEID,PARENTID, @le:= IF (PARENTID = 0 ,0, IF( LOCATE( CONCAT('|',PARENTID,':'),@pathlevel) > 0 , SUBSTRING_INDEX( SUBSTRING_INDEX(@pathlevel,CONCAT('|',PARENTID,':'),-1),'|',1) +1 ,@le+1) ) levels , @pathlevel:= CONCAT(@pathlevel,'|',TRADEID,':', @le ,'|') pathlevel , @pathnodes:= IF( PARENTID =0,',0', CONCAT_WS(',', IF( LOCATE( CONCAT('|',PARENTID,':'),@pathall) > 0 , SUBSTRING_INDEX( SUBSTRING_INDEX(@pathall,CONCAT('|',PARENTID,':'),-1),'|',1) ,@pathnodes ) ,PARENTID ) )paths ,@pathall:=CONCAT(@pathall,'|',TRADEID,':', @pathnodes ,'|') pathall FROM lf_ctrl_trade, (SELECT @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv ORDER BY PARENTID,TRADEID ) srcORDER BY TRADEID
方案二:
创建函数
DROP FUNCTION IF EXISTS queryChildrenTrade;CREATE FUNCTION `queryChildrenTrade` (myid INT)RETURNS VARCHAR(4000)BEGINDECLARE sTemp VARCHAR(4000);DECLARE sTempChd VARCHAR(4000); SET sTemp = '$';SET sTempChd = cast(myid as char); WHILE sTempChd is not NULL DOSET sTemp = CONCAT(sTemp,',',sTempChd);SELECT group_concat(TRADEID) INTO sTempChd FROM lf_ctrl_trade where FIND_IN_SET(PARENTID,sTempChd)>0;END WHILE;return sTemp;END;
如何查询:
select * from lf_ctrl_trade where FIND_IN_SET(TRADEID, queryChildrenTrade(3000))
原创文章,作者:admin,如若转载,请注明出处:https://www.qq65hfghe5.com/tg/65581.html