I have a table:
Id | child | parent
1 67 0
2 69 67
3 79 68
4 76 69
7 75 68
I want to select records until parent id is zero
All records in same table
I have a table:
Id | child | parent
1 67 0
2 69 67
3 79 68
4 76 69
7 75 68
I want to select records until parent id is zero
All records in same table
To quote from How to represent a data tree in sql
some databases, particularly MySQL, have some issues in handling this model, because it requires an ability to run recursive queries which MySQL lacks.
A long but very thorough explanation of the problem (and its solution) can be found here: Managing hierarchical data in mysql
TL/DR: If you want to solve this problem with a single query then you need to change your tree to a nested list structure - which is a bit harder to understand but more efficient to handle in mysql.
Let's take this tree:
In your adjacency list format this would look like this
id | text | parent
1 A
2 B 1
3 C 1
4 D 3
5 E 3
6 F 1
Getting all parents of node D is not easy.
Now we convert this to a nested set:
0_________________A__________________11
1_B_2 3_______C_______8 9_F_10
4_D_5 6_E_7
id | text | lft | rgt
1 A 0 11
2 B 1 2
3 C 3 8
4 D 4 5
5 E 6 7
6 F 9 10
Now getting all parents of node D is easy:
SELECT p.* FROM nestedset p
INNER JOIN nestedset o ON o.lft > p.lft AND o.rgt < p.rgt
WHERE o.text == "D"
As for how to do other operations, follow the link i posted.