Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL, get all child with permissions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading