简体   繁体   中英

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. 1 student can have 1 or many modules, however, 1 module can technically have 0 or more students. How would I implement this in a database? Thanks.

This is an N:N relationship. The answer is that you have to create a middle table that will create a link between your Student table and your Module table.

The middle table, which you can name StudentByModule for example, will hold a key identifying the student and another key identifying the module. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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