I have this parent table. my goal is to find out given an id all of its decendents. For example for the following table:
+----------+-----+
| parentId | id |
+----------+-----+
| 0 | 1 |
| 0 | 2 |
| 0 | 3 |
| 0 | 4 |
| 1 | 5 |
| 1 | 11 |
| 5 | 12 |
| 12 | 13 |
| 14 | 15 |
| 19 | 20 |
| 20 | 24 |
+----------+-----+
given the parent 0 i would like to get:
+----+
| Id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 11 |
| 12 |
| 13 |
+----+
My Restircions/Notes: 1. I can have 4 levels of hierarchy at the worst case. 2. my DB is MYSQL ( that means i cannot write recursive query ) . 3. the table id_to_id is pretty small.. 100 rows tops.
the solution i was thinking about was something like this sql query :
SELECT DISTINCT(T.Id)
FROM(
SELECT t1.Id
FROM id_to_id AS t1
LEFT JOIN id_to_id AS t2 ON t2.parentId = t1.Id
LEFT JOIN id_to_id AS t3 ON t3.parentId = t2.Id
LEFT JOIN id_to_id AS t4 ON t4.parentId = t3.Id
WHERE t1.parentId = 0
UNION ALL
SELECT t2.Id as lev2
FROM id_to_id AS t1
LEFT JOIN id_to_id AS t2 ON t2.parentId = t1.Id
LEFT JOIN id_to_id AS t3 ON t3.parentId = t2.Id
LEFT JOIN id_to_id AS t4 ON t4.parentId = t3.Id
WHERE t1.parentId = 0
UNION ALL
SELECT t3.Id as lev3
FROM id_to_id AS t1
LEFT JOIN id_to_id AS t2 ON t2.parentId = t1.Id
LEFT JOIN id_to_id AS t3 ON t3.parentId = t2.Id
LEFT JOIN id_to_id AS t4 ON t4.parentId = t3.Id
WHERE t1.parentId = 0
UNION ALL
SELECT t4.Id as lev4
FROM id_to_id AS t1
LEFT JOIN id_to_id AS t2 ON t2.parentId = t1.Id
LEFT JOIN id_to_id AS t3 ON t3.parentId = t2.Id
LEFT JOIN id_to_id AS t4 ON t4.parentId = t3.Id
WHERE t1.parentId = 0) as T
WHERE T.Id IS NOT NULL;
BUT then that inner query will be performed 4 times ( am i wrong here? ) :
FROM id_to_id AS t1
LEFT JOIN id_to_id AS t2 ON t2.parentId = t1.Id
LEFT JOIN id_to_id AS t3 ON t3.parentId = t2.Id
LEFT JOIN id_to_id AS t4 ON t4.parentId = t3.Id
WHERE t1.parentId = 0) as T
So my questions are:
- any ideas for making it work without joining 4 times? Or another smart solution for that query?
- How to write query that can perform the same on each id on the table ( can i do that?) without a given parameter - something like :
+----+------------+ | Id | decedents | +----+------------+ | 0 | 1,2,3,4,...| | 1 | 5,11,... | +----+------------+
Thanks, Ido