SQL - n:m relations | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

SQL - n:m relations

What about n:m relations? Is there any way in SQL to avoid creating two sub-tables (each having an 1:n relation) for such cases?

11th Jan 2017, 3:59 PM
H3LL0FR14ND
H3LL0FR14ND - avatar
5 Answers
+ 6
Unfortunately the only way to do many to many relations us to have an extra table. So say for example you were modeling classes at a university. You might have a table that models a student and another that models classes. Each student might belong to 0 or more classes and a class has one or more students. To model this relationship you'll need a third table that stores just the student's and the class' primary keys. This third table will have foreign key relationships to the other two tables. I wish there was a better way to do this but SQL doesn't really provide an alternative.
11th Jan 2017, 4:07 PM
James Durand
James Durand - avatar
+ 4
@James Durand Such a pity, but I already suspected that. I assume there might not even exist any alternative no matter whatsoever database-language one is using.. Nevertheless thanks for the help!
11th Jan 2017, 4:17 PM
H3LL0FR14ND
H3LL0FR14ND - avatar
+ 4
@James Durand, and et al, For your student & classes example... consider that 3rd "relationship" table to be your "enrollments" table... often times enrollments are what the university gets paid for. The data model does not have to limit that table to only two columns. For a retailer, the sales transaction table is often similar (one entry may relate to customerID, orderID, productID, salespersonID, deliverySiteID, etc). And yes, it is possible to record Many-to-Many relationships without a relationship table (or junction table), but you lose referential integrity and incur substantial performance penalties trying to reconstruct those relationships dynamically (at query time).
16th Jan 2017, 2:31 AM
Daniel Oliver
+ 2
If you use a NoSQL database there are definitely options but this wouldn't be a good enough reason on its own to go that route.
11th Jan 2017, 4:20 PM
James Durand
James Durand - avatar
- 1
My code
14th Jan 2017, 2:45 AM
Rizal
Rizal - avatar