Do they have a table for all categories and another for all sub-categories (and another for the sub-sub-categories and so on), or what? How do all the levels go around communicating with each other?
I'm a noob getting started on a project that might have that level of complexity and I am having a hard-time wrapping my head around that.
I'm working with Rails but I'd also appreciate answers in database schemas, pointers to further reading etc.
I am assuming that you are dealing with hierarchical data here.
You just need two tables. One of the tables is for the categories and relationships between the categories. For example:
CategoryID CategoryName ParentCategoryID
----------------------------------------
1 Computers NULL
2 Programming 1
3 Games 1
4 Python 2
The other table is for storing the data associated with the categories. For example:
CategoryID ItemID Description
----------------------------------------------
4 1 Book – Programming in Python
3 1 World of Warcraft
The first table contains a foreign key column that links the subcategories to their parent categories. This is known as the “Adjacency List Model”. This model has the advantage of being simple to understand and doing various things (e.g. retrieving the path to the Python category – /Computers/Programming/Python) with this model can be done quite easily with client-side code (if you don’t mind the performance cost because you may need to make multiple queries to the database). However, it can be mindboggling if you try to do it in full SQL. For example, retrieving the path for a category will require self-joins.
Another way of structuring this table is to think of the categories and sub-categories as sets and subsets (known as the “Nested Set Model”). It’s hard to explain this model without diagrams, and the article Managing Hierarchical Data in MySQL seems to do a better job in explaining the concepts (both “Adjacency List” and “Nested Set” models).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With