Satu-ke-satu: Gunakan kunci asing ke tabel yang direferensikan:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
Anda juga harus meletakkan batasan unik pada kolom kunci asing (addess.student_id
) untuk mencegah beberapa baris dalam tabel anak (address
) dari menghubungkan ke baris yang sama dalam tabel yang direferensikan (student
).
Satu-ke-banyak :Gunakan kunci asing di banyak sisi hubungan yang menautkan kembali ke sisi "satu":
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Banyak-ke-banyak :Gunakan tabel persimpangan (contoh):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Contoh kueri:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y