MySQL存儲過程可以實現(xiàn)多級目錄樹型結(jié)構(gòu)的存儲和查詢。具體實現(xiàn)方式如下:
DELIMITER $$ CREATE PROCEDURE sp_get_tree(IN parent_id INT) BEGIN DECLARE isLeaf INT DEFAULT 0; DECLARE nodeId INT; DECLARE nodeName VARCHAR(50); DECLARE cursor_node CURSOR FOR SELECT id, name, is_leaf FROM tree WHERE parent_id = parent_id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET @flag = 0; SET @flag = 1; OPEN cursor_node; FETCH cursor_node INTO nodeId, nodeName, isLeaf; WHILE @flag DO IF isLeaf THEN SELECT CONCAT(LPAD("", 2*(parent_id-1), "-"), '-', nodeName) AS tree_name FROM tree WHERE id = nodeId; ELSE CALL sp_get_tree(nodeId); END IF; FETCH cursor_node INTO nodeId, nodeName, isLeaf; END WHILE; CLOSE cursor_node; END $$ DELIMITER ;
以上代碼中,存儲過程中通過遞歸查詢子節(jié)點實現(xiàn)了多級目錄樹型結(jié)構(gòu)的查詢,并使用LPAD和CONCAT函數(shù)實現(xiàn)了樹狀結(jié)構(gòu)的展示。