mysql分层数据,递归cte,同时排除条件上的分支

rfbsl7qr  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(276)

我有一张table A 用这种结构

| id | parent_id | permission_type |

我使用下面的递归cte查询来获取id为1的对象的所有子对象(在本例中)。

with recursive B (              
                id,
                parent_id,
                permission_type) as (
select          id,
                parent_id,
                permission_type
from       A
where      (id = '1')
union all
select     
                t.id,
                t.parent_id,
                t.permission_type
from        A t
inner join B
        on t.parent_id = B.id 
)select * from B;

问题是我不想用 permission_type = "no_permission" 也不是他们的孩子或后代。我想排除从具有 permission_type = "no_permission" .

所以在本例中,我希望输出为:(排除树的红色分支)

| id | parent_id | permission_type |
====================================
| 1  |    null   |      ''         |
| 2  |    1      |      ''         |
| 3  |    2      |      ''         |

这在mysql中是可能的吗?如果是,怎么办?
注意:还有其他权限类型,但我认为在这里输入这些信息是不必要的。我关心的只是基于“no\u permission”权限类型排除分支的能力

gt0wga4j

gt0wga4j1#

WITH RECURSIVE 
b (id, parent_id, permission_type) AS ( SELECT id,
                                               parent_id,
                                               permission_type
                                        FROM a
                                        WHERE id = 1
                                      --  AND permission_type != "no_permission"
                                      UNION ALL
                                        SELECT a.id,
                                               a.parent_id,
                                               a.permission_type
                                        FROM a
                                        INNER JOIN b ON a.parent_id = b.id
                                        WHERE a.permission_type != "no_permission"
                                      )
SELECT * 
FROM b;

相关问题