简体   繁体   中英

How to associate sub-category to a field in database?

I am creating a MySQL database. I have a column named, name of the product. The product has one Main Category. However, it can belong to n-number of sub categories. I need to map these sub categories to that product. How can I do that?

Table1 - Product Info
Columns - ID , Name , MainCategory , SubCategory (Not Sure Exactly)

Table2 - MainCategory
Columns - ID , Name

Table3 - SubCategory
Columns - ID , Name

Table1 has 1-to-1 relationship to Table2. How do I map Table1 to Table3? Am I doing this wrong?

Thought : I want to do it in the manner so that whenever I click on any subcategory name on a website, I get a list of all the products under that category. Just like it happens in Online Stores Website.

Example : The product External Hard Drive will come under Computer Accessories . But I want to give it sub-categories like offer_running , 500GB , SomeCompanyName , black etc.

Hope I explained my question. Please help me in the designing of database. I have got all the basics of DBMS, but I don't know how to involve keywords and to store & map them in a database.

How about the following structure:

Table1 - Product Info
Columns - ID , Name , Main_Category_ID

Table2 - Category
Columns - ID , Name

Table3 - Product_Category
Columns - ID , Product_ID , Category_ID , Name

Then you could use the following query to get all of the get all of the information:

SELECT p.*, c.Name 
FROM [Product Info] p
INNER JOIN Product_Category pc ON p.ID = pc.Product_ID
INNER JOIN Category c ON pc.Category_ID = c.ID

Notice that in the Product Info table I added a Main_Category_ID field. If you really need to identify the main category then this would work:

SELECT p.ID, p.Name, NULL AS MainCat, c.Name AS SubCat
FROM [Product Info] p
INNER JOIN Product_Category pc ON p.ID = pc.Product_ID
INNER JOIN Category c ON pc.Category_ID = c.ID
UNION 
SELECT p.ID, p.Name, c.Name AS MainCat, NULL AS SubCat
FROM [Product Info] p
INNER JOIN Category c ON p.Main_Category_ID = c.ID

First of all, if table 1 and table 2 have a 1-1 relationship, there is no need for having two separate tables. This will make query processing faster and will eliminate the need for an extra join.

Can you clarify what the ID column in table 3 refers to? Is this an unique ID for table 3 or the ID from table 1?

If former is the case, then you need to have the ID column of table 1 as the foreign key in table 3. That will resolve your issues.

Hope that helps.

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