mysql遞歸查詢(父級,子集)

①查詢父級html

表:函數

先給表船艦函數:ui

 1 CREATE FUNCTION `getParentList`(rootId varchar(100))   
 2 RETURNS varchar(1000)   
 3 BEGIN   
 4 DECLARE fid varchar(100) default '';   
 5 DECLARE str varchar(1000) default rootId;   
 6   
 7 WHILE rootId is not null  do   
 8     SET fid =(SELECT PID FROM DIGUI WHERE ID = rootId);   
 9     IF fid is not null THEN   
10         SET str = concat(str, ',', fid);      
11         SET rootId = fid;   
12     ELSE   
13         SET rootId = fid;   
14     END IF;   
15 END WHILE;   
16 return str;  
17 END

而後能夠查詢父級了:spa

1 SELECT
2     *
3 FROM
4     digui
5 WHERE
6     FIND_IN_SET(id, getParentList('9'))

 ②查詢子集(參考:http://www.javashuo.com/article/p-zxxtyaef-et.htmlcode

表:htm

SQL:查詢id=12的子集blog

 1 SELECT
 2     t3.id,
 3     t3.parent_id,
 4     t3.menu_name 
 5 FROM
 6     (
 7     SELECT
 8         t1.id,
 9         t1.parent_id,
10         t1.menu_name,
11     IF
12         ( find_in_set( parent_id, @pids ) > 0, @pids := concat( @pids, ',', id ), 0 ) AS ischild 
13     FROM
14         ( SELECT id, parent_id, menu_name FROM menu t WHERE t.STATUS = 1 ORDER BY parent_id, id ) t1,
15         ( SELECT @pids := 12 ) t2 
16     ) t3 
17 WHERE
18     ischild != 0

結果:get

相關文章
相關標籤/搜索