通过MySQL中的父ID和where子句获取所有子代

时间:2018-12-20 12:27:55

标签: mysql hierarchical-data recursive-query

我有一个表,在同一表中存储id和parent_id。我想要一个递归查询,它接受parent_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'用户类型。让我知道如何获取此信息?

2 个答案:

答案 0 :(得分:1)

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

排除被排除的父母的孩子

因此,即使孩子不是编辑者,如果他们的祖先之一是编辑者,也应将他们排除在外。这意味着您应该在最里面的查询中排除记录:在其中添加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字段,然后包装执行过滤器的查询,如下所示:

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'

同样,这里的结果还将包括记录,这些记录的父级(父级,祖父母,祖父母,祖父母,...)可能未完全包含(因为其中一些可能是编辑者)。

答案 1 :(得分:0)

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

相关问题