I'd like to select a root item and it's children as much performant as possible. I prefer using the nested sets model, but this time the table structure is following the adjacency model. More about nested sets and adjancency model.
I've a dependencies-table
, and a items-table
.
Dependencies table
dependency_id | item_id | child_id
1 | 1 | 4
2 | 2 | 5
3 | 4 | 7
4 | 7 | 3
5 | 9 | 3
6 | 1 | 2
Items table
item_id | name | info
1 | Item A | 1st Item
2 | Item D | 2nd Item
3 | Item C | 3rd Item
4 | Item D | 4th Item
5 | Item E | 5th Item
6 | Item F | 6th Item
SQL, first try
# selecting children (non-recursive)
# result: 4, 2
SELECT
child_id AS id
FROM `dependencies_table`
WHERE item_id = 1
I need this SELECT recursive.
Desired output
# children of item #1
dependency_id | item_id | child_id
1 | 1 | 4 // 1st level
6 | 1 | 2 // 1st level
2 | 2 | 5 // 2nd level, 1->2->5
This case should be very common, but I'm wondering I couldn't find a best-practice for now. Please note: it's MySQL, so I'm not able using CTE!
How would you solve this problem? Thanks in advance!
Edit: I found an interesting thread, but my problem isn't solved yet. So, please don't close this Question.
Edit 2: Here's an interesting PHP solution, but unfortunately not what I actually want.