MySQL存儲(chǔ)過(guò)程可以實(shí)現(xiàn)多級(jí)目錄樹型結(jié)構(gòu)的存儲(chǔ)和查詢。具體實(shí)現(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 ;
以上代碼中,存儲(chǔ)過(guò)程中通過(guò)遞歸查詢子節(jié)點(diǎn)實(shí)現(xiàn)了多級(jí)目錄樹型結(jié)構(gòu)的查詢,并使用LPAD和CONCAT函數(shù)實(shí)現(xiàn)了樹狀結(jié)構(gòu)的展示。