通过父 ID 和 mysql 中的 where 子句获取所有子项
Get all children by parent id and where clause in mysql
我有一个 table 将 id 和 parent_id 存储在同一个 table 中。我想要一个接受 parent_id 作为参数和 returns 所有第 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'
用户类型。如果可能的话让我知道如何获得这个?
我认为创建联合比使用子查询更容易,但是如果没有看到您正在使用的表的设计,我恐怕无法给您很好的例子。
有两种可能的解释。根据最近的评论,我了解到您需要第一个:
排除 children 排除 parents
所以即使 children 不是编辑,如果他们的祖先之一是编辑,他们也应该被排除在外。这意味着您应该排除最内层查询中的记录:在此处添加 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))
包括 children 个,排除 parent 个
在此解释中,您希望编辑 children 被包括在内,而不管他们的任何祖先是否被排除在外。
在 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'
因此,这里的结果还将包括 parent-hierarchy(parent、grandparent、grand-grandparent、...)可能不是的记录完全包括在内(因为其中一些可能是编辑器)。
我有一个 table 将 id 和 parent_id 存储在同一个 table 中。我想要一个接受 parent_id 作为参数和 returns 所有第 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'
用户类型。如果可能的话让我知道如何获得这个?
我认为创建联合比使用子查询更容易,但是如果没有看到您正在使用的表的设计,我恐怕无法给您很好的例子。
有两种可能的解释。根据最近的评论,我了解到您需要第一个:
排除 children 排除 parents
所以即使 children 不是编辑,如果他们的祖先之一是编辑,他们也应该被排除在外。这意味着您应该排除最内层查询中的记录:在此处添加 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))
包括 children 个,排除 parent 个
在此解释中,您希望编辑 children 被包括在内,而不管他们的任何祖先是否被排除在外。
在 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'
因此,这里的结果还将包括 parent-hierarchy(parent、grandparent、grand-grandparent、...)可能不是的记录完全包括在内(因为其中一些可能是编辑器)。