table:
id parent_id
--------------
a_1 NULL
a_2 NULL
b_1 a_1
c_1 b_1
d_1 c_1
Now, I have id:d_1
How can I get a_1
,b_1
,c_1
in one SQL query? (d_1
's ancestor ids)?
table:
id parent_id
--------------
a_1 NULL
a_2 NULL
b_1 a_1
c_1 b_1
d_1 c_1
Now, I have id:d_1
How can I get a_1
,b_1
,c_1
in one SQL query? (d_1
's ancestor ids)?
SELECT c.id, b.id, a.id
FROM T
INNER JOIN T AS c on T.parent_id=c.id
INNER JOIN T AS b ON c.parent_id = b.id
INNER JOIN T as a ON b.parent_id = a.id
assuming your table's named T. untested though. not sure what happens if d doesn't have three parents, probably you don't get a thing, might try LEFT JOIN for those cases to obtain NULL values for the great parents. Also, the last JOIN isn't really necessary because you could simply select b.parent_id instead of a.id but, you know, just to drive home the pattern ;)
I really don't think you can do this in a simple SQL statement, it's a fundamental limitation of the SQL language.
Here is a heinous stored procedure that does roughly what you want (for SQL Server). So you would need to do something like this.