子查询和多表 [英] Subqueries and multi tables
问题描述
我有一个关于我遇到的问题的基本问题:
I have a basic question regarding a problem I faced:
假设我有这些表的模型:
Let's say I have this model with these tables :
Food(Quantity, Animal_id)
Race(Race_code, Race_name)
Animal(Animal_id, Race_code)
我被要求通过选择查询找到每个种族的总食用量.
I have been asked to find the total quantity eaten by each race with select query.
(当然是使用SUM函数.显示也需要Race_name
)
(Of course by using SUM function. Race_name
is also required for the display)
但是我不知道将这些表的属性链接起来从数量到种族名称(我只知道我的推理会是这样的Quantity->animal_id->race_code->;race_name
).有什么帮助吗?
But I don't know to link the attributes of these tables to go from the quantity to the race name (I only know that my reasoning will be like this Quanity->animal_id->race_code->race_name
). Any help ?
推荐答案
看起来像加入,不是吗?未聚合的列(在本例中为 race_name
)必须放入 group by
子句中.
Looks like a join, doesn't it? Columns that aren't aggregated (race_name
in this case) have to be put into the group by
clause.
select r.race_name,
sum(f.quantity) sum_quantity
from race r join animal a on a.race_code = r.race_code
join food f on f.animal_id = a.animal_id
group by r.race_name;
这篇关于子查询和多表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!