I have a MySQL query that I thought works fine to get all the ancestors of each node, starting from the top node, right up to its immediate node. However, when I added level 5 to the nested set, it broke.
The following are examples of tables, queries, and SQL scripts:
Four levels of nested dialing:
CREATE TABLE Tree (title varchar(20) PRIMARY KEY, `tree` int, `left` int, `right` int); INSERT Tree VALUES ("Food", 1, 1, 18), ('Fruit', 1, 2, 11), ('Red', 1, 3, 6), ('Cherry', 1, 4, 5), ('Yellow', 1, 7, 10), ('Banana', 1, 8, 9), ('Meat', 1, 12, 17), ('Beef', 1, 13, 14), ('Pork', 1, 15, 16);
Request:
SELECT t0.title node ,(SELECT GROUP_CONCAT(t2.title) FROM Tree t2 WHERE t2.left<t0.left AND t2.right>t0.right ORDER BY t2.left) ancestors FROM Tree t0 GROUP BY t0.title;
The returned result for node Banana is Food,Fruit,Yellow - Perfect. You can see it here SQL Fiddle - Level 4
When I run the same query in a table below level 5, nodes of the fifth level are returned in the wrong order:
CREATE TABLE Tree (title varchar(20) PRIMARY KEY, `tree` int, `left` int, `right` int); INSERT Tree VALUES ("Food", 1, 1, 24), ('Fruit', 1, 2, 13), ('Red', 1, 3, 8), ('Cherry', 1, 4, 7), ('Cherry_pie', 1, 5, 6), ('Yellow', 1, 9, 12), ('Banana', 1, 10, 11), ('Meat', 1, 14, 23), ('Beef', 1, 15, 16), ('Pork', 1, 17, 22), ('Bacon', 1, 18, 21), ('Bacon_Sandwich', 1, 19, 20);
The return result for Bacon_Sandwich is Bacon,Food,Meat,Pork , which is not correct, it should be Food,Meat,Pork,Bacon . You can see it here SQL Fiddle - 5 levels
I am not sure what is happening because I am not well versed in subqueries. Can anyone shed some light on this?
EDIT AFTER RESEARCH:
Wow !! It seems like writing all this, and reading the order with GROUP_CONCAT gave me some inspiration.
Adding ORDER BY to the actual GROUP_CONCAT function and removing it from the end of the subquery solved the problem. Now I get Food,Meat,Pork,Bacon for node Bacon_Sandwich
SELECT t0.title node ,(SELECT GROUP_CONCAT(t2.title ORDER BY t2.left) FROM Tree t2 WHERE t2.left<t0.left AND t2.right>t0.right ) ancestors FROM Tree t0 GROUP BY t0.title;
I still donβt know why. If ORDER BY at the end of a subquery works for 4 levels, but not for 5?!?!
If someone can explain what the problem is and why moving ORDER BY corrects it, I would be very grateful.