I have table
task_categories: id, name, parent_id, is_public, …
How can I get tree where is_public = 1 for any root.
If is_public = 0 it shouldn’t return any child for this element.
Example:
structure is:
| id | name | parent_id | is_public |
|---|---|---|---|
| 1 | Task 1 | null | 1 |
| 2 | Task 1.1 | 1 | 0 |
| 3 | Task 1.1.1 | 2 | 1 |
| 4 | Task 1.2 | 1 | 1 |
| 5 | Task 1.2.1 | 4 | 1 |
So, I want return all descendants for Task 1.
In this case it should return Task 1.2 and Task 1.2.1. It shouldn’t return Task 1.1.1 even it’s public because parent is private (is_public = 0).
>Solution :
Using a common table expression:
-- including `Task 1.1`
WITH RECURSIVE cte AS (
SELECT id,name,parent_id,is_public
FROM mytable where parent_id is null
union all
SELECT mytable.id, mytable.name, mytable.parent_id, mytable.is_public
FROM cte
INNER JOIN mytable ON cte.id = mytable.parent_id and cte.is_public=1
)
SELECT * FROM cte;
or
-- not including `Task 1.1`
WITH RECURSIVE cte AS (
SELECT id,name,parent_id,is_public
FROM mytable where parent_id is null
union all
SELECT mytable.id, mytable.name, mytable.parent_id, mytable.is_public
FROM cte
INNER JOIN mytable ON cte.id = mytable.parent_id and mytable.is_public=1
)
SELECT * FROM cte;
see: DBFIDDLE