patternMinor
Set the primary key for many to many relationship
Viewed 0 times
theprimaryformanysetkeyrelationship
Problem
For the two relations, Customer and Equipment:
There is a limited number of equipments (stock) and upon hiring I need to store the date of hire and the expected return date.
I sketched this:
What I'm not sure about is what is the primary key of Hire_Equipment?
If it is customer_id and equip_id then the customer wont be able to hire the equipment again in the future?
Did I mis-designed the schema? do you suggest a better approach?
There is a limited number of equipments (stock) and upon hiring I need to store the date of hire and the expected return date.
I sketched this:
Table Customer
customer_id
Table Equipment
equip_id
available_stock
Table Hire_Equipment
customer_id
equip_id
hiring_date
expected_return_dateWhat I'm not sure about is what is the primary key of Hire_Equipment?
If it is customer_id and equip_id then the customer wont be able to hire the equipment again in the future?
Did I mis-designed the schema? do you suggest a better approach?
Solution
In a practical system (as opposed to a textbook problem) you would want to have some kind of transaction identifier on any transaction like hiring one or more pieces of equipment. Assuming you are running an equipment hiring business, your transactions would probably have to account for letting out multiple pieces of equipment at once. Therefore you need to add an order table as follows:
and your Hire_Equipment table would change as follows:
Note that the
This design allows a customer to hire a piece of equipment more than once on a given date but it prevents hiring the same equipment more than once on the same order - which is what you would expect.
Table Order
order_id
order_dateand your Hire_Equipment table would change as follows:
Table Hire_Equipment
customer_id (PK)
order_id (PK)
equip_id (PK)
expected_return_dateNote that the
hiring_date has been normalised up to the Order level, but expected_return_date has been left at the item level, since you might want to allow a single order to contain a mixture of rental periods.This design allows a customer to hire a piece of equipment more than once on a given date but it prevents hiring the same equipment more than once on the same order - which is what you would expect.
Code Snippets
Table Order
order_id
order_dateTable Hire_Equipment
customer_id (PK)
order_id (PK)
equip_id (PK)
expected_return_dateContext
StackExchange Database Administrators Q#27770, answer score: 3
Revisions (0)
No revisions yet.