mysql根据父节点递归查询所有子节点
程序员文章站
2022-05-30 16:38:57
...
mysql根据父节点递归查询所有子节点,以此备录。
根据一个父节点查询所有子节点(包含自身)
SELECT au.id
FROM (SELECT * FROM t_app_user WHERE parent_id IS NOT NULL) au,
(SELECT @pid := '1') pd
WHERE FIND_IN_SET(parent_id, @pid) > 0
AND @pid := concat(@pid, ',', id)
union select id from t_app_user where id = '1';
根据多个父节点查询所有子节点(包含自身)
SELECT au.id
FROM (SELECT * FROM t_app_user WHERE parent_id IS NOT NULL) au,
(SELECT @pid := '1,4') pd
WHERE FIND_IN_SET(parent_id, @pid) > 0
AND @pid := concat(@pid, ',', id)
union select id from t_app_user where FIND_IN_SET(id,@pid) > 0;
如果不想查询结果包含自身,去掉后边的union