I want to create product filter for multiple categories. User will select for ex. Mobile phones category via form select element and then there will be showed options for this category which user can choose, for ex. Color, processor,…
And I want to know how best way how to set up database tables for this purpose. My idea is to create three tables:
1. Items
Id | Item_Name | Cat_Id | Option_1 | Option_2 | ...
1 | Samsung S20 | 1 | blue | Intel | ...
2 | iPhone 5 | 1 | red | AMD | ...
3 | T-shirt | 2 | red | NULL | ...
2. Categories:
Id | Cat_Name |
1 | mobiles |
2 | clothes |
3. Options
Id | Option | Values |
1 | color | red, blue, purple, ... |
2 | processor | Intel, AMD, ... |
4. Cats_Opts
Id | Cat_id | Option_id |
1 | 1 | 1 |
2 | 1 | 2 |
Problem is, that in my structure many fields will be empty bcz for ex. clothes category will not have value for option_2.
Is this good way how to do db structure for this purpose?
2
Answers
So if I can summary it, finally, it can look like this:
A database is normalized, at least in part, when there’s a single column for each type of information. So when you see more than one column having the same information, that part of the database is not "normalized".
Similarly when you see lists of data in a column, such as
red, blue, purple
in a single column, this is a candidate for normalization. (Not to say there is no place for "un-normalized" data in a relational database.)Another opportunity for normalization is when a column has the same data repeated in more than one rows, such as:
…where
blue
andIntel
are repeated.In this case, and particularly when the same value or option may be applied to more that one item, the duplicated options can be eliminated using linking tables:
To compile all the options into fewer reference tables:
Then, of course,
JOIN
them all together.Outputs:
Try it here: https://onecompiler.com/mysql/3yj627ggs