简体   繁体   English

一对多/零对多关系?

[英]One-to-many/Zero-to-many relationship?

I'm having a little bit of trouble with the following relationship between two tables: 我在两个表之间的以下关系有点麻烦:

Say, there's two tables, one being Student, the other being Module. 假设有两个表,一个表是Student,另一个表是Module。 1 student can have 1 or many modules, however, 1 module can technically have 0 or more students. 1个学生可以有1个或多个模块,但是从技术上讲1个模块可以有0个或多个模块。 How would I implement this in a database? 如何在数据库中实现呢? Thanks. 谢谢。

This is an N:N relationship. 这是N:N关系。 The answer is that you have to create a middle table that will create a link between your Student table and your Module table. 答案是必须创建一个中间表,该中间表将在Student表和Module表之间创建链接。

The middle table, which you can name StudentByModule for example, will hold a key identifying the student and another key identifying the module. 中间表(例如,您可以将其命名为StudentByModule)将包含一个标识学生的键和另一个标识模块的键。 This assumes that you have created a proper key in both tables. 假设您在两个表中都创建了正确的键。

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/many-to-many.html http://en.tekstenuitleg.net/articles/software/database-design-tutorial/many-to-many.html

As for the case where a module is not assigned to any student this will be modelled by the absence of rows in the middle table linking the module to a student. 至于没有将模块分配给任何学生的情况,将通过在中间表中没有将模块链接到学生的行来建模。

Also note that in order to associate a student to a module, you will first have to make sure that both the student and the modules are created first. 还要注意,为了将学生与模块相关联,您首先必须确保首先创建了学生和模块。

It's actually a many-to-many relationship. 这实际上是一个多对多的关系。 You implement it using a third table to link your tables 您使用第三个表来实现它以链接表

Student table
--
StudentId PK
...


Module table
---
ModuleId PK
...


StudentModule table
---
StudentId FK
ModuleId FK

The last table has a record only if there's a link between a student and a module. 仅当学生和模块之间存在链接时,最后一个表才有一条记录。 You insert primary keys of both Student and Module tables to make them linked. 您插入Student表和Module表的主键以使其链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM