Get all children by parent id and where clause in mysql

社会主义新天地 提交于 2020-01-30 11:42:08

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/53868711/get-all-children-by-parent-id-and-where-clause-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!