4个不同表中按日期时间分组的值的总和

问题描述

我有4个不同的表,每个表如下所示:

--------------------------------
|id|  value|           datetime|
--------------------------------
| 1| 2554.0|  26-08-20 14:36:15|
| .|      .|                   |
| .|      .|                   |
| .|      .|                   |
--------------------------------

我需要的很简单,但我不确定如何实现。

我需要将4个不同表中具有相同日期时间的每个值相加。

示例:

Time is: 26-08-20 14:36:15

Table 1: 2554.0; 
Table 2: 4143.0; 
Table 3: 9432.0; 
Table 4: 1662.0;

我应该能够得到:17791

解决方法

您可以使用union all。如果要所有这些值,则:

select datetime,sum(value)
from ((select id,value,datetime,1 as which from table1) union all
      (select id,2 as which from table2) union all
      (select id,3 as which from table3) union all
      (select id,4 as which from table4)
     ) t
group by datetime;

如果只需要所有四个表中的值,则添加:

having count(distinct which) = 4

如果每个表中没有 重复项,则可以使用join获取所有表中的值:

select datetime,sum(value)
from table1 t1 join
     table2 t2
     using (datetime) join
     table3 t3
     using (datetime) join
     table4 t4
     using (datetime)
group by datetime;

这仅在所有四个表中返回datetime值。不幸的是,如果您希望将所有值加起来,MySQL不支持full join,因此union all方法更通用-更安全,因为它处理每个表中的重复项。