MYSQL查询上级和下级

时间:2021-10-30 02:55:38

读取 group_id为4的所有下级

SELECT ID.level, DATA.* FROM( 
SELECT 
@ids as _ids, 
( SELECT @ids := GROUP_CONCAT(group_id) 
FROM rbac_group 
WHERE FIND_IN_SET(parent_group_id, @ids) 
) as cids, 
@l := @l 1 as level 
FROM rbac_group, 
(SELECT @ids :=4, @l := 0 ) b 
WHERE @ids IS NOT NULL 
) id, rbac_group DATA 
WHERE FIND_IN_SET(DATA.group_id, ID._ids) 
ORDER BY level, group_id

读取 group_id为6的所有下级

SELECT ID.level, DATA.* FROM( 
SELECT 
@id as _id, 
( SELECT @id := parent_group_id 
FROM rbac_group 
WHERE group_id = @id 
) as _pid, 
@l := @l 1 as level 
FROM rbac_group, 
(SELECT @id := 6, @l := 0 ) b 
WHERE @id > 0 
) ID, rbac_group DATA 
WHERE ID._id = DATA.group_id 
ORDER BY level;