I have a table in MySQL that looks like this:
CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) NOT NULL,
`data` VARCHAR(255),
`otherid` int(11),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
With some rows:
ID|STUFF|OTHERID
-----------------
1 |"stuff"| 2
2 | "x" | 4
3 | "y" | NULL
4 | "z" | NULL
I want to select first the row where data = "stuff" and then all the following rows (which could be "infinite") where the next rows are found by id = lastrow.otherid
. Like this:
ID|STUFF|OTHERID
-----------------
1 |"stuff"| 2
2 | "x" | 4
4 | "z" | NULL
If there is no row with data = something
, then no rows should be selected.
Any suggestions?
Best Answer
About 4.5 years ago, I wrote a rather aggressive stored procedure to traverse data stored in a hierarchy and bring back all descendants within that table : Find highest level of a hierarchical field: with vs without CTEs
I took the code from the GetFamilyTree function and wrote it as a procedure for you
STORED PROCEDURE
SAMPLE DATA FROM YOUR QUESTION
SAMPLE DATA FROM YOUR QUESTION LOADED
STORED PROCEDURE EXECUTED
CAVEAT # 1
Writing this using
UNION SELECT
was not practical since the depth of the tree of data is not known. This code will handle any depth of data.CAVEAT # 2
This code does not handle circular references in data (Where (id,otherid) and (otherid,id) coexist in this table).