问题描述
category subcategory subcategory
jewelry body nose ring,arm ring,ear ring
men ring,ear ring
我有多个 category-> subcategory-> subcategory
,因此该表如何在MySQL中?
I have multiple category->subcategory->subcategory
so how will be the table for this in MySQL?
推荐答案
像这样构造表:
Id Category ParentId
1 Jewelry NULL
2 Body 1
3 nose ring 2
4 arm ring 2
5 ear ring 2
-
-
这称为自引用表,即 ParentId
列包含 NULL
或同一表的 Id
列中的值。
This is called Self-Referencing Table i.e. ParentId
columns contains either NULL
or value from the Id
column of same table.
所以只要您必须知道给定类别的所有直接
,您只需创建一个查询:子类别
so whenever you have to know all the direct subcategories
of a given category
, you simply create a query like :
Select * from CategoryMaster where ParentId = 2;
执行此操作,您将获得该子类别的所有子类别正文
。
doing this you will get all the sub-categories for the sub-category Body
.
现在,关于此数据结构最好的部分是,对于任何给定的子类,您都可以拥有n级子类-category和具有3列(最少)的同一张单表。
Now, the best part about this data-structure is that you can have n-levels of sub-categories for any given sub-category and same single table with 3 columns (at minimum) will do.
这篇关于我的SQL多个类别-子类别-子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!