Subject | Self-referencing table SQL question |
---|---|
Author | diwic2 |
Post date | 2006-06-05T11:13:36Z |
I have a self-referencing table, something like:
id integer
name varchar(98)
parentid integer (references another row in the same table)
say I have these rows:
ID ParentID Name
1 <null> World
2 1 Europe
3 2 Sweden
4 2 Germany
5 3 Stockholm
6 3 Gothenburg
7 4 Berlin
Now is there a smart SQL query that for one or more id's, will return
the actual rows, including their ancestors? That is, if I do a select
"where ID=5", I would like rows 5,3,2 and 1 returned ("Stockholm",
"Sweden","Europe","World").
id integer
name varchar(98)
parentid integer (references another row in the same table)
say I have these rows:
ID ParentID Name
1 <null> World
2 1 Europe
3 2 Sweden
4 2 Germany
5 3 Stockholm
6 3 Gothenburg
7 4 Berlin
Now is there a smart SQL query that for one or more id's, will return
the actual rows, including their ancestors? That is, if I do a select
"where ID=5", I would like rows 5,3,2 and 1 returned ("Stockholm",
"Sweden","Europe","World").