通过mysql中的parent-id和where子句获取所有子项



我有一个表,它将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'用户类型。如果可能的话,让我知道如何得到这个?

可能有两种解释。从最近的一条评论中,我知道你需要第一条:

排除被排除父母的子女

因此,即使孩子们不是编辑,如果他们的祖先之一是编辑,他们也应该被排除在外。这意味着您应该排除最内部查询中的记录:在其中添加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))

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

在这种解释中,您希望编辑器的孩子被包括在内,而不管他们的祖先是否被排除在外。

select列表中添加user_type字段,然后包装执行筛选的查询,如下所示:

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'

因此,这里的结果还将包括父层次结构(父、祖父母、曾祖父母…(可能没有完全包括的记录(因为其中一些可能是编辑器(。

我认为创建关节比使用子查询更容易,但如果没有看到您正在使用的表的设计,恐怕我无法真正为您提供好的示例。

最新更新