简体   繁体   中英

Sub categories Hierarchy

I designed a SQL structure to represent categories and their subcategories.

I have 3 tables:

articles
articles_categories
categories

Articles table:

id,title,content

Categories table:

id, title, parent_id

articles_categories:

id,article_id,category_id

No problem with SQL, but now - lets say i'm on article id 5 article id 5 has - 3 categories, that 2 of them has parents, and the main has '0' as parent.

How do I fetch them all efficiently? (lets say for - breadcrumbs).

thanks!

Unless the depth of the category hierarchy is fixed, you cannot do this in MySQL with your current model (adjacency list). You'd have to traverse the hierarchy using several SQL statements in a loop.

If the category hierarchy is fairly static, you can "precompute" the tree by using:

  • Path enumeration
  • Nested sets
  • Closure table

All of the above, trades write performance for read performance. Google or search SO for any of the above and you will find examples of how to implement it.

Quite often, I find that storing the data in a adjacency list (because of best matches the data model) and caching a copy of the tree in the application is good enough, but that depends on your requirements of course :)

This should do the job:

select * from articles_categories 
left join categories on categories.id = articles_categories.category_id 
where article_id=1;

+------+------------+-------------+------+--------+-----------+
| id   | article_id | category_id | id   | title  | parent_id |
+------+------------+-------------+------+--------+-----------+
| NULL |          1 |           1 |    1 | first  |         0 |
| NULL |          1 |           2 |    2 | second |         1 |
| NULL |          1 |           3 |    3 | third  |         2 |
+------+------------+-------------+------+--------+-----------+

Additionally, I would remove the "id" column from associative table articles_categories .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM