1

If I have a category tree where there is an undetermined level of subcategories, is it possible to get the entire tree of categories in one query (without any loops)?

This is a possible scenario:

 category_id  parent_id   Name
0           null        Home
1           null        Auto
2           0           Living Room
3           2           Couches
4           2           TV
5           4           Home Theatre
6           5           Cables

If you notice, Cables lineage is such that: Home > Living Room > TV > Home Theatre > Cables

Right now, I get the parent category of the current category and keep looping until I get to the parent category that has a null parent category. I know this part has been asked before. However, I'm wondering is there a better way to structure this table so that I don't have to run X amount of queries (or subqueries)? I considered for instance adding a 4th column called parents or something that would have the entire lineage in a comma separated list (such that in this case parents would be: 5,4,2,0. However this seemed tacky and inefficient (and easy to break). Is there a better mechanism available?

4
  • 1
    Yes, there are a better structures than simple trees to model hierarchical data in databases. Have a look at e.g. nested sets or closure tables. Closure tables are similar to what you have in mind at the end.
    – Solarflare
    Commented Dec 8, 2016 at 15:07
  • I second the suggestion for closure tables. amzn.to/2gfNBc5 provides a good description of various approaches, including closure tables, to solving this problem. Commented Dec 8, 2016 at 15:23
  • I found this really useful when I was doing something similar: mikehillyer.com/articles/managing-hierarchical-data-in-mysql
    – Dan
    Commented Dec 8, 2016 at 15:27
  • Tyvm. Never heard of a "closure table" before. Reading the articles now. Commented Dec 8, 2016 at 18:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.