Reputation: 5012
I have table as
+-------------+----------------------+--------------------+
| category_id | name | parent_category_id |
+-------------+----------------------+--------------------+
| 1 | Pizzas | NULL |
| 2 | Cheese Pizzas | 1 |
| 3 | Spicy Pizzas | 1 |
| 4 | Shakes | NULL |
| 5 | Milk Shakes | 4 |
I have only single level nesting and its going to be the same
I wish to retrieve the rows like
Pizza
Cheese Pizzas
Spicy Pizzas
Shakes
Milk Shakes
Is there something like "Trees" In MySQL as in Oracle, I did read the article http://ftp.nchu.edu.tw/MySQL/tech-resources/articles/hierarchical-data.html
Changing the table structure seems more feasible when there is dynamic levels of nesting, for my case its just going to be 1 throughout
Any Suggestions?
Upvotes: 0
Views: 81
Reputation: 125925
You could use a self-join and do something like:
SELECT parent.category_id, parent.name AS parent, child.name AS child
FROM my_table parent JOIN my_table child
ON parent.parent_category_id IS NULL
AND child.parent_category_id = parent.category_id
ORDER BY parent.category_id, child.category_id
See it on sqlfiddle.
Or even group the results, if so desired:
SELECT parent.name, GROUP_CONCAT(child.name ORDER BY child.category_id)
FROM my_table parent JOIN my_table child
ON parent.parent_category_id IS NULL
AND child.parent_category_id = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_id
See it on sqlfiddle.
Upvotes: 3