1.

How should data be structured to support Join Operations in a many-to-many relationship?

Answer»

The many-to-many relationship is a bit more complex than the one-to-many relationship.

Example: Consider a Student table and a Class table, both of which have many-to-many relationships: any student can be enrolled in many classes, and any class can have many students. It means an individual student may have many classes, and there may be many students in each class. 

Student Table

Student_IDStudent_Name
1Asha Bisht
2Rohit Sharma
3Karan Tacker

Class Table

Class_IDClass_Name
1Maths
2Science
3English
4Physical Education
5Computer Science

In this case, we cannot add the primary key of one table to that of another, or to both of them, as this only stores a single relationship, while what we really need is multiple relationships. Thus, we use a concept called a bridging table or joining table. The joining tables are those that are placed between two other tables in a many-to-many relationship and are intended to hold a record for each combination of the two other tables. It may seem like quite a chunk of work, but the process is simple and provides a much better data structure. In this case, we will create a new table called ClassEnroll maintaining two columns, one for each of the primary keys of the other table. Those columns store separate records for every class and student combination.

ClassEnroll Table

Student_IDClass_ID
11
13
24
22
34
31



Discussion

No Comment Found