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](https://multimusen.dk/wp-content/uploads/theDatabase-300x182.jpg)
![The ER-Diagram transformed to tables in PhpMyAdmin](https://multimusen.dk/wp-content/uploads/tablesAndRelations-300x123.png)
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.
Leave a Reply