mysql預存程序之遞迴查詢

來源:互聯網
上載者:User

標籤:

    對一顆樹型結構儲存的表進行遞迴查詢,使用navicat for mysql 建立預存程序 pro_show_knowledge, 參數 --  IN `rootId` int   ,通過知識點查詢所有子節點資料並插入到暫存資料表 tmp_knowledge_data中。

    注意深度的設定 , set max_sp_recursion_depth = 100 ; 這句話必須加上。

BEGIN#設定遞迴查詢的層深上限 set max_sp_recursion_depth = 100;#建立暫存資料表tmp_knowledge_data,用於儲存某個知識點下的所有子節點資料    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_knowledge_data(`id` int(11) NOT NULL,                          `name` varchar(50) DEFAULT NULL,                          `pId` int(11) DEFAULT NULL,                          `create_time` datetime DEFAULT NULL,                          `modify_time` datetime DEFAULT NULL,                  `nDepth` int(11) DEFAULT NULL,                  `is_parent` int DEFAULT NULL,                          PRIMARY KEY (`id`),                          UNIQUE KEY `id_index` (`id`) USING BTREE,                          KEY `pid_index` (`pId`) USING BTREE)  ENGINE=InnoDB DEFAULT CHARSET=utf8;     DELETE FROM tmp_knowledge_data;     CALL pro_create_childLst(rootId,0);     select * from tmp_knowledge_data;END

子節點插入暫存資料表之前判斷資料是否為父節點,並將isparent屬性存入暫存資料表

BEGIN#開始迴圈DECLARE done INT DEFAULT 0;DECLARE b INT;DECLARE cur1 CURSOR FOR SELECT id FROM mooc_si_knowledge_tree where pId=rootId and delete_flag=0;DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;OPEN cur1;FETCH cur1 INTO b;if done =0THENinsert into tmp_knowledge_data (id,name,pId,create_time,modify_time,nDepth,is_parent) (select id,name,pId,create_time,modify_time,nDepth,1 AS is_parent from mooc_si_knowledge_tree where id = rootId); ELSEinsert into tmp_knowledge_data (id,name,pId,create_time,modify_time,nDepth,is_parent) (select id,name,pId,create_time,modify_time,nDepth,0 AS is_parent from mooc_si_knowledge_tree where id = rootId);END IF;WHILE done=0 DOCALL pro_create_childLst(b,nDepth+1);FETCH cur1 INTO b;END WHILE;        CLOSE cur1;#迴圈結束END


mysql預存程序之遞迴查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.