Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases Querying Relational Databases Table Relationships Table Relationships Review

Allan Oloo
Allan Oloo
8,054 Points

Many to Many relation examples

I am having a hard time conceptualizing the many to many concept in database. I understand that if we have many to many table we make a third table. Can someone give me a example of why we need do that?

1 Answer

Florian Tönjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

Hi Allan,

great question. As an example lets say we have favorite recipes and users. A user can have many favorite recipes and a favorite recipe can have many users who favor it. That's a many to many relationship.

Without a third table you would have duplicate entries in one of the two tables. You'd either have multiple recipe entries, for different users who favor it, with the same primary key in the recipe table, or multiple user entries, for different favored recipes, with the same primary key in the users table, both is not possible because the primary key has to be unique.

Therefore we create a new table in which we connect both primary keys of the tables as foreign keys which together create the primary key of the new table.

Someone correct me if I'm wrong.

Kind Regards, Florian