0

Is there a way using only MySQL query to select ID=? and its related children and grandchildren and so on... until there are no more.

Example:

enter image description here

ID 1: Has is the parent, ID 2: Is the child of the parent, IDs 3-8: Are the grandchildren

I want to get results such as:

if ID=1, select 1,2,3,4,5,6,7,8
OR ID=2, select 2,3,4,5,6,7,8
OR ID=3, select 3

Something like:

select from TABLE where id=? while related>0 select from TABLE where related=? end while
lc.
  • 113,939
  • 20
  • 158
  • 187
Maciek Semik
  • 1,872
  • 23
  • 43
  • 1
    Possible duplicate of [How to do the Recursive SELECT query in MySQL?](https://stackoverflow.com/questions/16513418/how-to-do-the-recursive-select-query-in-mysql) – lc. Oct 17 '17 at 08:26
  • 1
    You can probably create a function for returning you first level children for a record and call that function recursively. – Ketan Patil Oct 17 '17 at 08:27
  • 1
    If you can change table structure than you should really use [nested sets](https://en.wikipedia.org/wiki/Nested_set_model). There are many realisations for all popular frameworks: [laravel](https://github.com/lazychaser/laravel-nestedset), [doctrine](https://github.com/blt04/doctrine2-nestedset), [yii2](https://github.com/creocoder/yii2-nested-sets) and others. – marv255 Oct 17 '17 at 12:16

0 Answers0