We dcide to add a extra column ancestors
where we put all the ancestor parent of a child separated by a ,
like this
+----+-----------+------------+------------+
| ID | ID_parent | name | ancestors |
+----+-----------+------------+------------+
| 7 | 5 | .... | ,7, |
| 10 | 7 | .... | ,10,7, |
| 11 | 5 | .... | ,11,5, |
| 20 | 7 | .... | ,20,7, |
| 30 | 10 | .... | ,30,10,7, |
| 45 | 20 | .... | ,45,20,7, |
In my case i choose to put the child and it's ancestors between ,
and i start and i finish with the ,
maybe different approach can be used depend on situation.
So now we can easily get the child of a parent or get the parent ancestor of a child.
- To found all child of a parent we use
LIKE %,idparent,%
- To found all parents of a child we split the field
ancestors
of this child
and we can get all ancestor so we loop over them.