MySQL从表1中选择一个SUM,并在它们连接的SUM表2中选择它

时间:2016-07-18 16:20:52

标签: mysql database join

我有一张桌子"猫"其中包含预算列,项目ID列和ID列。孩子到这里是表"时钟",其中包含cat_id和total_time。

我需要

SELECT the SUM of cats.budget WHERE project_id = 1

以及

SELECT SUM(clocks.total_time) WHERE cats.id = clocks.cat_id

我在JOIN查询中返回正确的SUM时遇到问题,因为它通常会为JOIN中找到的每个时钟记录实例复制cats表的SUM值。

示例查询我已尝试

SELECT a SUM(table1.column1), JOIN table2 WHERE table1.id = table2.cat_id, and SELECT SUM(table2.column2)

谢谢!

2 个答案:

答案 0 :(得分:1)

似乎你需要一个内部联接

select sum(cats.budget)/count(clocks.*), SUM(clocks.total_time)
from cats 
inner join clocks on cats.id = clocks.cat_id
where cats.project_id =1;

答案 1 :(得分:0)

您需要JOIN已经汇总的 clocks表:

select t1.id, sum(t1.budget) as total_budget, t2.total_time
from cats as t1
inner join (
   select cat_id, SUM(total_time) as total_time
   from clocks 
   group by cat_id) as t2 on t1.id = t2.cat_id
where t1.project_id =1
group by t1.id

上面查询中使用的派生表会返回每SUM total_time cat_idt2.total_time。该查询适用于MySQL。对于SQL Server,您需要在group by子句中添加{{1}}字段。