通过mysql中的父id和where子句获取所有子级

idv4meu8  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(634)

我有一个表,在同一个表中存储id和parent\u id。我需要一个递归查询,它接受parent\u id作为参数,并返回n级的所有子节点。为此,我使用这个代码,并为我正常工作。

select  id,
        name,
        parent
from    (select * from tablename
         order by parent, id) tablename,
        (select @pv := '1') initialisation
where   find_in_set(parent, @pv) > 0
and     @pv := concat(@pv, ',', id)

我的问题从这里开始:我想添加where子句和结果集,但无法做到这一点。在结果集中,我得到的用户类型如下 'admin', 'editor' .
我想删除 'editor' 结果集中的用户类型。如果可能的话让我知道如何得到这个?

f5emj3cl

f5emj3cl1#

有两种可能的解释。从最近的评论中,我了解到您需要第一个:

排除被排除父母的子女

因此,即使孩子不是编辑,如果他们的祖先之一是编辑,他们也应该被排除在外。这意味着您应该排除最内部查询中的记录:添加 where 在那里:

select  id,
        name,
        parent_id,
        user_type
from    (select * from p
         where user_type <> 'editor'
         order by parent_id, id) products_sorted,
        (select @pv := '19') initialisation
where   find_in_set(parent_id, @pv)
and     length(@pv := concat(@pv, ',', id))

包括被排除在外的父母的子女

在这种解释中,您希望包含编辑器子级,而不管是否要排除它们的任何祖先。
添加 user_type 中的字段 select 列出并 Package 执行筛选的查询,如下所示:

select  *
from    (
        select  id,
                name,
                parent_id,
                user_type
        from    (select * from p
                 order by parent_id, id) products_sorted,
                (select @pv := '19') initialisation
        where   find_in_set(parent_id, @pv)
        and     length(@pv := concat(@pv, ',', id))
) as sub
where user_type <> 'editor'

同样,这里的结果还将包括父层次结构(父、祖父母、外祖父母等)可能没有完全包括在内的记录(因为其中一些可能是编辑器)。

eagi6jfj

eagi6jfj2#

我认为创建一个联合比使用子查询更容易,但是如果没有看到您正在使用的表的设计,恐怕我不能给您一个很好的例子。

相关问题