从不同的mysql表中获取时间总和

时间:2018-02-10 11:40:49

标签: php mysql

是否有可能,如果可以,怎么样? 从这样的2个或更多表中得到总时间:

表1

id, racer_nr, total_time_spend
1, 315 , 03:01:40
1, 312 , 06:01:40
1, 313 , 10:01:40

表2

id, racer_nr, total_time_spend
1, 315 , 07:01:40
1, 312 , 15:15:00
1, 313 , 10:01:40

需要从所有表中获取每个racer_nr的total_time_spend的总和。 至少有5个,为了简单而给你2个

2 个答案:

答案 0 :(得分:1)

drop table if exists t,t2;

create table t(id int, racer_nr int, total_time_spend time);
insert into t values
(1, 315 , '03:01:40'),
(1, 312 , '06:01:40'),
(1, 313 , '10:01:40');
create table t2(id int, racer_nr int, total_time_spend time);
insert into t2 values
(1, 315 , '07:01:40'),
(1, 312 , '15:15:00'),
(1, 313 , '10:01:40');



select t.racer_nr, sec_to_time(sum(spendsecs))
from
(
select t.racer_nr , time_to_sec(total_time_spend) spendsecs
from t 
union all
select t.racer_nr , time_to_sec(total_time_spend) spendsecs
from t2 t
) t
group by racer_nr

+----------+-----------------------------+
| racer_nr | sec_to_time(sum(spendsecs)) |
+----------+-----------------------------+
|      312 | 21:16:40                    |
|      313 | 10:01:40                    |
|      315 | 10:03:20                    |
+----------+-----------------------------+
3 rows in set (0.00 sec)

在此处阅读日期时间功能https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

答案 1 :(得分:0)

我希望这能解决你的问题。

SELEC SUM(table1.total_time_spend+ table2.total_time_spend) Total 
From table1, table2 
WHERE table1.racer_nr = table2.racer_nr 
group by table1.racer_nr 
order by Total