How can I structure a table so that the field remains atomic?
-
06-07-2019 - |
Question
I have a shopping cart in which I have to keep track of stock, and this includes stock with attributes. For example:
shirt
-- blue, small = 50
-- blue, medium = 22
-- blue, large = 53
-- red, small = 15
etc...
These fields are currently separated by commas in the database and the IDs would be as follows:
1,3
1,4
1,5
2,3
where each number represents a specific attribute (1=blue,3=small). The problem is that this then becomes very hard to work with as the data is not atomic in the database, but I cannot think how to structure the table, as there could be infinitely many combinations of items such as:
blue, small, long-sleeved
Can anybody suggest a better way of storing this information in the database? I thought of using lookup tables but this would not work due to the varying number of attributes.
Solution
Table: Shirt { shirt_id }
Table: ShirtAttributeDefinitions{ attribute_id , attribute_description }
Table: ShirtAttribute{ shirt_id , attribute_id }
this way, you can keep defining new ShirtAttributes by adding records to Table:ShirtAttributeDefinitions.
Example:
you have two shirts: { shirt_id:1 }, { shirt_id:2 }
you have five shirt attributes: {attribute_id:1, attribute_description:blue }, {attribute_id:2, attribute_description:small }, {attribute_id:3, attribute_description:ladies }, {attribute_id:4, attribute_description:red }, {attribute_id:5, attribute_description:men }
Now your first shirt is a blue small ladies shirt, and the second one is a red mens shirt. So your ShirtAttribute table will have these recrods:
{shirt_id:1, attribute_id:1}, {shirt_id:1, attribute_id:2}, {shirt_id:1, attribute_id:3}, {shirt_id:2, attribute_id:4}, {shirt_id:2, attribute_id:5}
Although this approach works, its best to make these attributes fields of the Shirt table. This way you can make sure that a shirt does not have both 'men' and 'ladies' attribute. This method is just a dirty approach that strictly conforms to your question.
jrh.
OTHER TIPS
what's wrong with an Attributes table?
create table Attributes (
Id int not null identity etc,
CartItemId int not null foreign-key etc,
Name nvarchar(32),
Value nvarchar(32)
)
?