I am practicing the database normalization, but sometimes I get confused about referencing. There is something I want to clarify first:
- The nested structure is given by the instructor, I don't know if it's correct or how it should be notated.
- I got the
SCAN
model, and the question specified the [PK] inside theSCAN
, which arestoreId
, and theproductId
.
Here is the question statement:
Customers take their goods to the checkout and purchase them: we record this as one purchase, consisting of quantities of different products. We must record each item scanned at the checkout, and the method used to pay for the purchase. We record which store the goods were purchased at. We do not identify our customers.
SCAN (storeId, storeAddress, purchaseId, whenPurchased, paymentMethod, (productId, productName, quantityPurchased))
I can see the [PK] and its association with the attributes, and derive it as follows:
Table1(storeId [PK], storeAddress)
Table2(purchaseId [PK], whenPurchased, paymentMethod, quantityPurchased)
Table3(productId [PK], productName)
However, when I tried to reference the foreign key, I choose to do like below. The reason is the purchase is around the customer, which is the Table2
. Therefore, when a customer purchases a product in a store, I need to reference the storeId
and the productId
as a foreign key, like the below:
Table1(storeId [PK], storeAddress)
Table2(purchaseId [PK], whenPurchased, paymentMethod, productId [FK], storeId [FK])
Table3(productId [PK], productName, quantityPurchased)
Sometimes I get confused about which Table should reference the other. For example, there are two table: department
and emp
. The emp
should reference departmentId
as a foreign key because each employee affiliated to at least one department, but the opposite is wrong. How can I determine the relationship between two entities and reference correctly?