I wrote about the recursive query and deletion of oracle and mysql before, this time I will add a recursive implementation of mysql.
1. Implementation principle
(1) Delete the temporary table
(2) Create a temporary table and empty it
(3) Use a temporary table to store the id list recursively traversed
(4) Query the id list from the temporary table
2. Recursively query the stored procedure code
Stored procedure function name: findMenuChildList(menuPid varchar(32))
BEGIN
DECLARE v_menu VARCHAR(32);
DECLARE done INTEGER DEFAULT 0;
-- 查询结果放入游标中,eguid原创
DECLARE C_menu CURSOR FOR SELECT d.menuid
FROM vnmp_menu d
WHERE d.pid = menuPid;
DECLARE CONTINUE HANDLER FOR NOT found SET done=1;
SET @@max_sp_recursion_depth = 10;
-- 传入的菜单id写入临时表,eguid原创
INSERT INTO tmp_menu VALUES (menuPid);
OPEN C_menu;
FETCH C_menu INTO v_menu;
WHILE (done=0)
DO
-- 递归调用,查找下级
CALL findMenuChildList(v_menu);
FETCH C_menu INTO v_menu;
END WHILE;
CLOSE C_menu;
END
3. Create a temporary table and get the data in the temporary table
Stored procedure function name: findMenuidArray(rootIds varchar(32))
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp_menu;
-- 创建临时表,eguid原创
CREATE TEMPORARY TABLE tmp_menu(menuid VARCHAR(32));
-- 清空临时表数据
DELETE FROM tmp_menu;
WHILE (done=0)
DO
-- 循环调用递归函数,eguid原创
CALL findMenuChildList(rootId);
END WHILE;
-- 删除父节点
DELETE FROM tmp_menu where menuid=rootId;
-- 从临时表查询结果
SELECT menuid FROM tmp_menu;
END
4. Call the query stored procedure
CALL findMenuidArray('1');
Result (the query is a list of ids, which can facilitate related query and recursive deletion):
0fc126c5e60942229ae50ebbfb60e5fd
41ceae53abc14ab68a77dc527b1c0e5d
4334b8670a9244699d68fe4d80eeb4e9
5d3c6ab1793f4e55816a99ac71e4431b
5. Recursively delete stored procedure implementation code
Stored procedure function name: removeMenuById( rootId varchar(32))
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmp_menu;
-- 创建临时表
CREATE TEMPORARY TABLE tmp_menu(menuid VARCHAR(32));
-- 清空临时表数据
DELETE FROM tmp_menu;
-- 发起调用
CALL findMenuChildList(rootId);
-- 不要删除父节点,删除时要同时删除父节点,eguid原创
#DELETE FROM tmp_menu where menuid=rootId;
-- 从临时表查询结果,eguid原创
-- 删除菜单
DELETE FROM vnmp_menu where menuid in(SELECT menuid FROM tmp_menu);
-- 删除菜单关联表,如果设置了外键就不需要执行这步,eguid原创
DELETE FROM vnmp_permission where associatedid in(SELECT menuid FROM tmp_menu);
END
4. Call the query stored procedure
CALL findMenuidArray('1');
result
update 4