r/DatabaseHelp • u/Agil7054 • Apr 10 '18
Help with a Ternary Relationship
In the relationship shown below, any teacher can recommend any book to any class. How can I change it so each teacher can only recommend one book to any specific class and that book can only be from a unique list for each teacher.
For example, Mr. Phillips can only recommend Frankenstein XOR Dracula XOR Strange Case of Dr. Jekyl to a class while Ms. Morgan can only recommend Jane-Eyre XOR Wuthering Heights XOR Moby-Dick to a class. And how do I make it so each teacher can only make a recommendation to a specific class once. So Mr. Phillips can recommend Dracula to class 1 and Ms. Morgan can also recommend Moby-Dick to class 1 but she can't also recommend Wuthering Heights to class 1.
3
u/wolf2600 Apr 10 '18
This sort of logic is applied at the application layer, not at the database layer.
Your application would have to query the DB to see if a certain book has been assigned already, then take appropriate action (either permitting the assignment or not) based on the query results.
These sorts of constraints do not go into the database schema design.
1
u/chrwei Apr 10 '18
maybe an additional table of teachers and books to define that limit, then add constraints, triggers, and logic in the app as needed based on what your DB engine supports.
1
u/cqell Apr 11 '18 edited Apr 13 '18
You need to create a junction table for teacher-course relationships with the primary key on teacher ID and course ID only. The key will only allow one record for each unique teacher-course relationship. The book_id field then becomes a field that describes each individual teacher-course relationship.
You need to create a junction table for teacher-book relationships with the primary key on teacher ID and book ID. The key will only allow one record for each unique teacher-book relationship. Then, create a multi-column foreign key on the teacher_course table that references both columns in teacher_book.
Updated ERD:
https://imgur.com/a/Zd3fk
Sample code (SQL Server):