Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. One-to-one: Use a foreign key to the referenced table:
  2.  
  3. student: student_id, first_name, last_name, address_id
  4. address: address_id, address, city, zipcode, student_id # you can have a
  5. # "link back" if you need
  6. You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).
  7.  
  8. One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
  9.  
  10. teachers: teacher_id, first_name, last_name # the "one" side
  11. classes: class_id, class_name, teacher_id # the "many" side
  12. Many-to-many: Use a junction table (example):
  13.  
  14. student: student_id, first_name, last_name
  15. classes: class_id, name, teacher_id
  16. student_classes: class_id, student_id # the junction table
  17. Example queries:
  18.  
  19. -- Getting all students for a class:
  20.  
  21. SELECT s.student_id, last_name
  22. FROM student_classes sc
  23. INNER JOIN students s ON s.student_id = sc.student_id
  24. WHERE sc.class_id = X
  25.  
  26. -- Getting all classes for a student:
  27.  
  28. SELECT c.class_id, name
  29. FROM student_classes sc
  30. INNER JOIN classes c ON c.class_id = sc.class_id
  31. WHERE sc.student_id = Y
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement