標籤:
對一顆樹型結構儲存的表進行遞迴查詢,使用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預存程序之遞迴查詢