慕雪6442864
一对一:使用引用表的外键: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还必须对外键列(addess.student_id)以防止子表中的多行(address)与引用表中的同一行相关(student).一对多*在连接到“一方”的关系的多个方面使用外键:teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side多对多使用连接表(例):student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table示例查询: -- 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