设计表格时如何实现一对一、一对多和多对多的关系? [英] How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

查看:53
本文介绍了设计表格时如何实现一对一、一对多和多对多的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能用一些例子解释一下如何在设计表格时实现一对一、一对多和多对多的关系?

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

这篇关于设计表格时如何实现一对一、一对多和多对多的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆