SQL: Many-to-Many and One-to-Many

Here’s a short tutorial on how to solve some basic SQL cardinalities. First have a look at the ER-diagram for the database and the resulting tables in PhpMyAdmin.

Many to many and one to many
Many to many and one to many
The ER-Diagram transformed to tables in PhpMyAdmin
The ER-Diagram transformed to tables in PhpMyAdmin

Many-to-Many

Many to many cardinalities may be solved like this:


SELECT cake, who
FROM cakes, costumers, likes
WHERE costumers.costumers_id = likes.costumers_id
AND cakes.cakes_id = likes.cakes_id

Note that there are two where clauses combined via AND.

One-to-Many

This cardinality is more easy:


SELECT inventory .* , costumers.who
FROM inventory, costumers
WHERE inventory.costumers_id = costumers.costumers_id

In the “many” table you simply connect via the “one” table’s id.

You can download and try out the samples from my Github Repository oneToMany_ManyToMany.

Read On

These samples are inspired by Ben Forta’s “MySQL Crash Course” Ch. 15 – 16.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enable Notifications OK No thanks

We use cookies - more information

Multimusen.dk will set a few cookies from Doubleclick, Google and the Social Media plugins they ay set some cookies. Some of my pages use APIs - such as YouTube, LinkedIn, Google Fonts, Google Maps, Mapbox, Spotify, Jetpack, Twitter, Facebook &c.. Such plugins may set the odd cookie.

Close