开发者

How to design a database which has single category and n number of sub categories using mysql

How to design a database which has single category and n number of sub categories using mysql

Example:

category

catId categoryName

1 cat 1

2 cat 2

3 cat 3

4 cat 4

subcategory

subCatId subCategoryName catId

1 subcat1 1

2 subcat2 1

3 subcat3 2

4 subcat4 开发者_StackOverflow中文版 4

For single category i can the above structure.

Like this if i am having n number of subcategories. In this case how should i design the db

thanks in advance


You could use just one table category with columns:

  • category_id
  • category_name
  • parent_category_id

For main categories You set parent_category_id to null and You're done. :)


using normalization

2 table if one subcategory has only 1 parent category

Category

id

SubCat

id

category_id (linking to category)

you would have 3 tables if one subcategory can be part of more then 1 category. Two with your data, and one for linking the two together

Category

id

name....

SubCategory

id

name ....

Sub_Cat_Link

category_id

subcategory_id

thus searching for all subcatergories of a category would result in a statment like

select * from SubCategory where category_id = idOfACategory


My principle is that if you can support N-levels you can support 2 levels (and not get in a pickle whan a fickle business user decides to have sub-sub-categories)

So i would create a categories table with the fields

  • id (autogenerated, sequence, UUID)
  • parent_id (foreign key to categories.id)
  • name
  • ...

In order to get the children of a category a

SELECT * FROM categories WHERE parent_id = :cat_id ;

You have to be a bit careful to keep it a acyclic directed graph, i.e. not create any loops, but that's about all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜