简体   繁体   中英

One to many join query through mapping table

This is probably a pretty basic thing to do but I can't quite get it to work and I can't find an example that does exactly what I am looking for. Say I have three tables:

animals: id, name, description
foods: id, name, description
animals_foods: animal_id, food_id

So I'm a new zookeeper and I want to see what kinds of foods all of the animals will eat. I want to see an output like this:

+--------+------------------------+
| animal |         foods          |
+--------+------------------------+
| lion   | beef,chicken,lamb      |
| hippo  | apples,hay,lettuce     |
| monkey | apples,bananas.carrots |
+--------+------------------------+

Join the tables together and group by the animals. group_concat can put together a list for each group

select a.name as animal_name, group_concat(f.name) as foods
from animals a
left join animal_foods af on af.animal_id = a.id
left join foods f on af.food_id = f.id
group by a.name

I use two separate tables for animals and foods and then a table called animals_foods allowing me to map an animal to the particular food.

Animal
1 - Lion
2 - Hippo
3 - Monkey

Foods
1 - Beef
2 - Chicken
3 - Lamb
4 - Apples
5 - Hay
6 - Lettuce
7 - Bananas
8 - Carrots

Then animals_foods table to map them accordingly with animal ID with corresponding food ID per row. (9 total).

Then do

SELECT * from animals a LEFT JOIN animals_foods af ON a.animal_ID = af.animal_ID LEFT JOIN foods f ON af.food_ID = f.food_ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM