This is an example, the names are fictitious.
On the one hand, we have suppliers who provide products to shops:
Suppliers
id name
1 GreatSupplier
2 SuperSupplier
On the other hand, we have shops that sell products to consumers:
Shops
id name supplier
1 NiceShop null
2 ShopShop null
3 Soop 1
4 CheapShop 1
5 MyShop 1
6 Shopping 2
There are shops that have their own prices like NiceShop or ShopShop, so they don't have suppliers. But there are shops that use the prices set by the supplier like Soop, CheapShop, MyShop or Shopping.
Then I want to show all the prices of the products that the shops show to their customers. Something like this:
NiceShop - Tomate: 1.23 // shop price
ShopShop - Tomate: 1.26 // shop price
Soop - Tomate: 1.21 // supplier 1 price
CheapShop - Tomate: 1.21 // supplier 1 price
MyShop - Tomate: 1.21 // supplier 1 price
Shopping - Tomate: 1.19 // supplier 2 price
Two options come to mind:
Option 1:
Products
id id_product id_shop id_supplier price
1 34 1 null 1.23
2 34 2 null 1.26
3 34 null 1 1.21
4 34 null 2 1.19
When displaying prices, if it is a row with id_shop I show it as is, but if it is a row with id_supplier I join the supplier and the shops.
Here I can't make a unique index between id_product-id_store-id_supplier and things like this could happen:
id id_product id_shop id_supplier price
5 34 3 null 1.21 // wrong
This should not happen as shop 3 has supplier 1 and this is already inserted in id 3.
Option 2:
Another option would be:
- If we insert a price from a shop that does not have a supplier, it is inserted as is.
- If we insert a price from a supplier, a join is made between the supplier and the shops and the same price is inserted several times. (same for updates)
Products
id id_product id_shop price
1 34 1 1.23 // shop price
2 34 2 1.26 // shop price
3 34 3 1.21 // supplier 1 price
4 34 4 1.21 // supplier 1 price
5 34 5 1.21 // supplier 1 price
5 34 6 1.19 // supplier 2 price
This option is a bit cleaner and allows me to create a single id_product-id_shop index but I am creating a lot of records with repeated prices, in this example it is duplicated 3 times but in my real environment it can be duplicated 50 times, and that translates into several extra gigabytes of database space.
Is there a better way to do this?