Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (4k points)

I have a MySQL table which is as follows:

idnameparent_id
19category10
20category219
21category320
22category421
.........

Now, I want to have a single MySQL query to which I simply supply the id [for instance say id=19] then I should get all its child ids [i.e. result should have ids '20,21,22']....

The hierarchy of the children is not known; it can vary....

I know how to do it using a for loop... but how to achieve the same using a single MySQL query?

1 Answer

0 votes
by (8.7k points)

Let’s create a hierarchical recursive query taking into consideration MYSQL version 8 and above.

This can be done with help of syntax :

with recursive cte (id, name, parent_id) as (

  select     id,

             name,

             parent_id

  from       products

  where      parent_id = 20

  union all

  select     p.id,

             p.name,

             p.parent_id

  from       products p

  inner join cte

          on p.parent_id = cte.id

)

select * from cte;

 

So here the value inn parent_id=20 is set to the id of the parent of whose descendants or child you want to select.

Curious about Mysql, check out this MYSQL Course by Intellipaat.

 

Related questions

0 votes
0 answers
asked Jun 24, 2021 in SQL by akhil.singh0123123 (320 points)
0 votes
1 answer
asked Jul 31, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer

Browse Categories

...