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 thi
There are two interpretations possible. From a recent comment I understand you need the first one:
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))
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).
I think it'll be easier to create a joint rather then using sub-queries, but without seeing the design of tables you are using I'm afraid I can't really give you good example.