I have a MySQL database, in which I have a table of monkeys:
id name
1 Alice
2 Bill
3 Donkey Kong
4 Edna
5 Feefee
I also have a table of bananas and where they were picked from.
id where_from
1 USA
2 Botswana
3 Banana-land
4 USA
Finally, I have a table matches that describes which bananas belong to which monkeys. Each monkey can only have one banana, and no monkeys can share a banana. Some monkeys may lack a banana.
id monkey_id banana_id
1 3 4
2 4 1
3 5 2
How can I use a single SQL statement to retrieve all the matches? For each match, I want the name of the monkey as well as where the banana is from.
I have tried the following 3 SQL statements, which work:
SELECT * FROM matchesSELECT * FROM monkeys WHERE id=[monkey_id from 1st SQL query]SELECT * FROM bananas WHERE id=[banana_id from 1st SQL query]
I feel that 3 SQL statements is cumbersome though. Any ideas on how I can just use a single SQL statement? I am just learning SQL and am monkeying around with the basics. Thanks!
Since some monkeys may lack a banana, that implies a
LEFT JOINbetweenmatchesandmonkeys. That will ensure all monkeys are listed, even if they have no bananas inmatches.Here is an example on SQLfiddle.com
I very highly recommend reading over Jeff Atwood’s (co-founder of Stack Overflow) excellent article explaining SQL joins.