Trying to get better at designing databases, I noticed I'm always stuck trying to solve variations of the exact same problem.
Here is an example using common requirements:
- An online store sells different categories of
product
. - The system must be able to retrieve the list of all product categories, say
food
andfurniture
. - A customer may order any product and retrieve his
order
history. - System must store specific properties depending on the product category ; say the
expiration_date
andcalories
for anyfood
product andmanufacture_date
for anyfurniture
product.
If it wasn't for requirement 4, the model could be quite straightforward:
Problem is trying to solve requirement 4. I thought of something like this:
In this approach, the relationship product-furniturerelationships product-furniture
and product-food is a supertypeproduct-food
are supertype-subtype (or superclass-subtype relationship ;subclass) associations; the primary key of the subtype is also a foreign key to the supertype primary key.
However, this approach can not guarantee the category
referenced via a foreign key to the product
will be consistent with its actual subtype. For instance, nothing stops me from setting food
category to a product tuple having a subtype recordrow in the Furniture
table.
I read various articles about inheritance in modelling relational databases, especially this one and this one which were very helpful but didn't solve my problem for the reason mentioned above. But whatever model I come with, I'm never satisfied with the data consistency.
How can I solve requirement 4 without sacrificing data consistency ? Am I going all wrong here ? If so, what would be the best way to solve this problem based on these requirements ?