众所周知,目前的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
) src
ORDER BY TRADEID
方案二:
创建函数
DROP FUNCTION IF EXISTS queryChildrenTrade;
CREATE FUNCTION `queryChildrenTrade` (myid INT)
RETURNS VARCHAr(4000)
BEGIN
DECLARE sTemp VARCHAr(4000);
DECLARE sTempChd VARCHAr(4000);
SET sTemp = '$';
SET sTempChd = cast(myid as char);
WHILE sTempChd is not NULL DO
SET 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))