user3067942
user3067942

Reputation: 41

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.

Upvotes: 4

Views: 18606

Answers (2)

Szymon
Szymon

Reputation: 43023

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.

Upvotes: 2

ApplePie
ApplePie

Reputation: 8942

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.

Upvotes: 4

Related Questions