简体   繁体   中英

How can I reference an intersection table of a many-to-many relationship?

I am creating a pharmacy database that handles prescriptions. When designing the database, I took into consideration that doctors can work at many offices, and an office can be home to many doctors, so I created the following many to many relationship:

doctor:

| id | name | // more

office:

| id | name | address | // more

doctors_offices:

| doctor_id | office_id |

I followed the design I've seen in my database textbooks as well as many online resources, but I'm now running into a little confusion when trying to create a prescription table. In this table I want to know not only which doctor wrote the prescription, but at which location.

I find myself having a few options:

  • Add an auto_increment key to the doctors_offices table to have a unique identifier for each dr/office pairing
  • Add a composite foreign key to the prescription table that references doctors_offices . (Is this possible?)
  • Add two foreign keys to prescription table. One that references doctors and one that references offices .

Which of these options is most normalized? I know that the third one is likely the least normalized, as it opens up the possibility that I select an office that a doctor does not belong to, but I felt important to mention as it might be a common instinct among some beginner database designers.

It is more flexible if you save the doctor_id as well as the location_id along with the prescriptions data. Otherwise, you will run into difficulties if a doctor moves to another office after already having given some prescriptions, unless you make a new entry for every time period a doctor was present in a certain office. Furthermore, you won't be able to properly depict the situation when, exceptionally, another doctor is present in the office and makes a prescription despite he or she has no office assignment.

People tend to become ingenious if the system prevents them from inserting data for a technical reason, you should always consider such exceptions, because they will occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM