En-til-en: Brug en fremmednøgle til den refererede tabel:
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
Du skal også sætte en unik begrænsning på kolonnen med fremmednøgle (addess.student_id
) for at forhindre flere rækker i den underordnede tabel (address
) fra at relatere til den samme række i den refererede tabel (student
).
En-til-mange :Brug en fremmednøgle på den mange side af forholdet, der linker tilbage til "en"-siden:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Mange-til-mange :Brug en krydstabel (eksempel):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Eksempelforespørgsler:
-- 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