I have a table which references itself, like this:
CREATE TABLE Foo (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
parent INT NULL,
name VARCHAR (30) NOT NULL,
FOREIGN KEY (parent) REFERENCES Foo(id) ON DELETE CASCADE);
Sample data:
id parent name
1 NULL a
2 NULL b
3 1 a1
4 1 a2
5 3 a1x
6 3 a2x
I want to write queries which will list the ancestors and decenders of a given row, e.g.
CALL find_ancestors('a1x')
Will return
id name
3 a1
1 a
and
CALL find_descendants('a')
Will return
id name
3 a1
5 a1x
How can I write these stored procedures for MySQL 5? Thanks
Bonus question for bounty: also select the distance of the returned row from the source and pass a maximum-distance parameter to the procedure, e.g.
CALL find_ancestors('a1x')
Will return
id name distance
3 a1 1
1 a 2
and
CALL find_ancestors_bounded('a1x',1)
Will return
id name distance
3 a1 1