For an e-shop I have
- Products table (id, name, price, description)
- Attributes table (attribute name, attribute value, product_id_fk)
Attribute name examples include: size, color and Attribute value examples include: XL, L, red, blue.
What is the best way to store stock levels? A “Bag” product may be in stock in L / red but not in XL / red whereas it may be in stock for all sizes in blue. There may be more than 2 attributes per product.
A third table is definitely needed. I think the best way to go is to have one column per attribute and an additional column for the product_id_fk. This would mean that if a new attribute is added for whatever product, an additional column needs to be created in the Stock table
Or is there a better way?
It looks as though you have a many-to-many relationship (i.e., products can have many attributes, and attributes can be associated with many products). Therefore your best design is to have a relationship table that contains the ids of both the product and the attribute.
This works if you have a unique row for each physical item. If you don’t then you need to have something that can handle the different types of the product.
PK = Primary Key
FK = Foreign Key