Skip to content
Advertisement

SQL Table with two relations or table with one relation and repeated rows

This is an example, the names are fictitious.

On the one hand, we have suppliers who provide products to shops:

Suppliers

On the other hand, we have shops that sell products to consumers:

Shops

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:

Two options come to mind:

Option 1:

Products

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:

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

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?

Advertisement

Answer

Most of the issues described can be solved by creating a common associated table for both shops and suppliers that is used to associate prices. In my example, I’ll call this the price_setters table.

A Shop’s Price-Setter is either itself or its supplier. This is enforced by the constraint on price_setters that the record has either a unique shop_id or a unique supplier_id, but not both.

prices has a FK to price_setters rather than shops or suppliers.

The only “anomaly” remaining is that there is no requirement in the schema for a shop or supplier to have a price_setter; however, that would just prevent you from assigning prices to the entity.

Edit: I moved the FKs between price_setters, shops, and suppliers into price_setters

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement