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

I have a table that stores id and parent_id in same table. I want a recursive query that accepts parent_id as an argument and returns all child nodes with nth level. For this I am using this code and working properly for me.

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)

My problem start from here: I want to add WHERE clause with result set but unable to do this. In result set I am getting user type like 'admin', 'editor'.

I want to remove 'editor' user type from result set. Let me know if possible to how to get this?

解决方案

There are two interpretations possible. From a recent comment I understand you need the first one:

Exclude children of excluded parents

So even if children are not editors, if one of their ancestors is an editor they should be excluded. That means you should exclude records in the inner most query: add the where there:

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))

Include children of excluded parents

In this interpretation you want editor children to be included irrespective of whether any of their ancestors are to be excluded.

Add the user_type field in the select list and then wrap that query that performs the filter, like this:

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'

So again, here the result will include also records of which the parent-hierarchy (parent, grandparent, grand-grandparent, ...) might not be completely included (because some of those could be editor).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值