-- 根据叶子节点查找所有父节点及其本身节点。如果只有叶子,剔除掉; 如果只有根,只显示一个秃顶的根 ;如果既有叶子又有根则显示.
DROP FUNCTION IF EXISTS `getParentLists`;
-- 参数1角色id 字符串逗号隔开; 参数2 角色id 个数
CREATE FUNCTION `getParentLists`(in_roleIds varchar(1000),count_roleIds INT)
RETURNS VARCHAR(3000)
BEGIN
-- 临时存放通过单个角色查找的单个menu_id
DECLARE sMenu_id_by_roleId VARCHAR(1000);
-- 临时存放通过单个角色查找的多个menu_id
DECLARE sMenu_ids_by_roleId VARCHAR(1000);
-- 临时存放通过多个角色查找的多个menu_id
DECLARE sMenu_ids_by_roleIds VARCHAR(1000);
-- 函数返回的menu_id 集合
DECLARE sReturn_menu_ids VARCHAR(3000);
-- 当前角色
DECLARE current_roleId_rows INT DEFAULT 0;
SET sMenu_id_by_roleId = '';
SET sMenu_ids_by_roleIds = '';
SET sReturn_menu_ids = '';
-- 循环多角色
WHILE current_roleId_rows < count_roleIds DO
-- 依次按角色取1条menu_id
SELECT menu_id
INTO sMenu_id_by_roleId
FROM Menu
WHERE FIND_IN_SET(auth_id, in_roleIds)
ORDER BY menu_id DESC
LIMIT current_roleId_rows, 1 ;
SET sMenu_ids_by_roleId = sMenu_id_by_roleId;
WHILE sMenu_ids_by_roleId IS NOT NULL DO
-- 判断是否是第一个,不加的话第一个会为空
IF sMenu_ids_by_roleIds != '' THEN
SET sMenu_ids_by_roleIds = CONCAT(sMenu_ids_by_roleIds,',',sMenu_ids_by_roleId);
ELSE
SET sMenu_ids_by_roleIds = sMenu_ids_by_roleId;
END IF;
-- 通过角色id 拼接 所有的父节点,重点拼接根节点,根节点置为字符NULL,用于后面判断是否有根
SELECT
GROUP_CONCAT(
CASE
WHEN sup_menu IS NULL THEN 'NULL'
ELSE sup_menu
END
)
INTO sMenu_ids_by_roleId
FROM Menu
WHERE FIND_IN_SET(menu_id,sMenu_ids_by_roleId) > 0;
END WHILE;
SET current_roleId_rows=current_roleId_rows+1;
-- 满足必须要有根节点NULL字符,则表明有根,否则不拼接给返回值
IF FIND_IN_SET('NULL',sMenu_ids_by_roleIds) > 0 THEN
SET sReturn_menu_ids = CONCAT(sReturn_menu_ids,',',sMenu_ids_by_roleIds);
END IF;
-- 清空通过单个角色查到的多个menu_id, 避免重复拼接
SET sMenu_ids_by_roleIds = '';
END WHILE;
RETURN sReturn_menu_ids;
END;
SELECT Menu.menu_id,Menu.sup_menu,Menu.auth_id
FROM Menu
WHERE FIND_IN_SET(menu_id, getParentLists('15,25,5,26',4))
ORDER BY Menu.menu_id+0 ASC;
SELECT Menu.menu_id,Menu.sup_menu,Menu.auth_id
FROM Menu
WHERE FIND_IN_SET(menu_id, getParentLists('17,5',2))
ORDER BY Menu.menu_id*1 ASC;
SELECT Menu.menu_id,Menu.sup_menu,Menu.auth_id
FROM Menu
WHERE FIND_IN_SET(menu_id, getParentLists('11,5',2))
ORDER BY Menu.menu_id*2 ASC;
|