来自两个不同表的mysql时间总和

时间:2013-02-19 22:38:14

标签: mysql nested sum

http://sqlfiddle.com/#!2/b814c/6/0

select listener, SEC_TO_TIME( SUM( TIME_TO_SEC(time))) as total_time, count(listener) as total_listened from db1 where date = "2013-02-20" group by listener

如何在此查询中添加db2值?

我尝试了嵌套查询,但运行速度太慢,并且只显示db2侦听器。

不同数据库中的两个表如果发生了变化。

结果应与此示例类似;

LISTENER    TOTAL_TIME  TOTAL_LISTENED
listener1   00:15:39    1
listener2   00:22:59    2
listener3   00:13:34    1

2 个答案:

答案 0 :(得分:1)

这是您的原始查询

select listener, SEC_TO_TIME( SUM( TIME_TO_SEC(time))) as total_time,
count(listener) as total_listened from db1 where date = "2013-02-20"
group by listener

尝试合并listenertime

然后,使用UNION

应用您的操作
SET @GivenDate='2013-02-20';
SELECT listener,SEC_TO_TIME( SUM( TIME_TO_SEC(time))) as total_time,
COUNT(listener) as total_listened
FROM
(
    SELECT listener,time FROM db1
    where date = @GivenDate
    UNION ALL
    SELECT listener,time FROM db2
    where date = @GivenDate
) A GROUP BY listener;

答案 1 :(得分:1)

你在找?

select listener, SEC_TO_TIME( SUM( TIME_TO_SEC(time))) as total_time, count(listener) as total_listened from 
(
  SELECT * FROM db1
  UNION ALL
  SELECT * FROM db2
) A
where date = "2013-02-20" group by listener

<强> SQL FIDDLE DEMO