mysql循環查詢樹狀數據

完整functionmysql

CREATE  FUNCTION `getChildList`(rootId BIGINT, table_name varchar(20)) RETURNS varchar(21845) CHARSET utf8
BEGIN 
       DECLARE str VARCHAR(21845) ; 
       DECLARE cid VARCHAR(21845) ; 
       
       SET str = ''; 
       SET cid =cast(rootId as CHAR); 
             
       WHILE cid is not null DO 
         SET str= concat(str,',',cid); 
                 IF table_name = 'tb_menu' THEN
                    SELECT group_concat(id) INTO cid from tb_menu where FIND_IN_SET(p_id,cid)>0;
                 ELSEIF table_name = 'tm_service_category' THEN
                    SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0;
                 ELSEIF table_name = 'tm_part_category' THEN
                    SELECT group_concat(pk_id) INTO cid FROM tm_part_category  where is_del = 0 and FIND_IN_SET(p_id,cid)>0;
                 end IF;
       END WHILE; 
       RETURN str; 
END

mysql查詢樹解析(此處只是簡單的循環並不是遞歸):
例如:調用以下sql

select getChildList(0,tm_service_category)

提煉執行語句spa

       WHILE cid is not null DO 
         SET str= concat(str,',',cid); 
            SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0;
       END WHILE; 
       RETURN str; 
        END

tm_service_category 表結構以下code

CREATE TABLE `tm_service_category` (
  `pk_id` bigint(20) unsigned NOT NULL COMMENT '主鍵',
  `name` varchar(50) DEFAULT NULL COMMENT '名稱',
  `p_id` bigint(20) unsigned DEFAULT NULL COMMENT '父節點',
  PRIMARY KEY (`pk_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

最主要的是p_id字段,表示父節點的pk_idblog

假設有數據以下遞歸

pk_id p_id name
1 0 a
2 1 b
3 1 c
4 2 d

樹結構以下:ci

整棵樹的根節點爲0,二級節點1,三級節點爲2,3,四級節點爲4get

模擬執行循環語句io

       WHILE cid is not null DO 
         SET str= concat(str,',',cid); 
            SELECT group_concat(pk_id) INTO cid FROM tm_service_category where FIND_IN_SET(p_id,cid)>0;
       END WHILE; 
       RETURN str; 
        END

getChildList(0,tm_service_category)

1,初始化cid=0
2,查找p_id爲0的全部節點拿到全部二級節點賦值給cid,cid=1,str=0,1
3,重複2步操做,查找p_id爲1的全部節點拿到全部二級節點賦值給cid,cid=2,3,str=0,1,2,3
4,重複2步操做,查找p_id爲2,3的全部節點拿到全部三級節點賦值給cid,cid=4,str=0,1,2,3,4
5,重複2步操做,查找p_id爲4的全部節點賦值給cid,沒找到任何節點,cid=null,退出循環table

相關文章
相關標籤/搜索