简体   繁体   English

多个类别/产品关系的数据库模式

[英]Database schema for multiple category/product relationship

I want to design a database for an e-commerce application with category/subcategory management. 我想为具有类别/子类别管理的电子商务应用程序设计数据库。 Please suggest a database schema where we can create categories and subcategories and add products to those categories. 请建议一个数据库架构 ,我们可以在其中创建类别和子类别,并将产品添加到这些类别。 Each product can have multiple categories and we can select products belong to multiple categories using a boolean database query 每个产品可以有多个类别,我们可以使用布尔数据库查询选择属于多个类别的产品

Thanks 谢谢

For categories and sub-categories to any level, along with products belonging to multiple categories, I would start with: 对于任何级别的类别和子类别,以及属于多个类别的产品,我将从以下开始:

Categories:
    category_id
    parent_category_id foreign key (Categories.category_id)
    ... other category information ...
    primary key (category_id)
Products:
    product_id
    ... other product information ...
    primary key (product_id_id)
ProductCategories:
    product_id foreign key (Products.product_id)
    category_id foreign key (Categories.category_id)
    primary key (category_id,product_id)
    index (product_id)

This way you can reach your goal of a hierarchy of categories as well as achieving a many-to-many relationship between products and categories. 通过这种方式,您可以实现类别层次结构的目标,并实现产品和类别之间的多对多关系。


You can select a product ID belonging to multiple categories (eg, 3 and 4) with a query like: 您可以使用以下查询选择属于多个类别(例如,3和4)的产品ID:

select a.product_id
from Products a, Products b
where a.product_id  = b.product_id
  and a.category_id = 3
  and b.category_id = 4

This would be best solved with a join table. 使用连接表可以最好地解决这个问题。 That is, you have a products table, and a categories table, each with a primary key. 也就是说,您有一个products表和一个categories表,每个表都有一个主键。 Then, you create a third table, which is the join table. 然后,您创建第三个表,即连接表。 It has 3 columns: it's primary key, category_id , and product_id . 它有3列:它的主键, category_idproduct_id Then, when you want to add a relationship between a product and a category, you insert a row into the join table with the category_id and product_id that are related. 然后,当您想要在产品和类别之间添加关系时,可以在连接表中插入一行,其中包含相关的category_idproduct_id You can then use the 3 tables together with joins to display the relationships. 然后,您可以将3个表与联接一起使用以显示关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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