How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?(设计表格时如何实现一对一、一对多和多对多的关系?)
问题描述
谁能用一些例子解释一下如何在设计表格时实现一对一、一对多和多对多的关系?
Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?
推荐答案
一对一: 使用引用表的外键:
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).
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).
一对多:在链接回一"方的关系的多方使用外键:
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
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
这篇关于设计表格时如何实现一对一、一对多和多对多的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:设计表格时如何实现一对一、一对多和多对多的关系?
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
