This may be a really simple problem to some people, but I’m finding it hard to understand.
The scenario:
I’m working with a school database.
I have a table which relates a class to a subject called ‘subject_class’.
A class can be a part of more than one subject, and a subject can can contain more than one class. So from what I understand, this is a many-to-many relation within a table.
An example of how the database would look:
subject_id class_id
1 14
1 15
2 14
*1 *14
As you can see, the same data can be entered into the table more than once (shown above with an asterisk). I want this to stop happening. My question is, what sort of key would this be? and why? or how could I stop the problem from happening?
I hope this makes sense, please let me know if it doesn’t, and I will provide more info.
Thanks in advance.
You would want to have a unique key on subject_id and class_id to prevent duplicates. But you NEED to make sure your application can either: handle the error thrown when you try to insert a value combination that is already there and make try to prevent it from submitting duplicates in the first place.
Alternatively, if you want the subsequent insert to overwrite the existing entry, you should look into whether your database software can handle ON DUPLICATE KEY UPDATE.