MySQL LEFT从第二个表

时间:2018-02-06 20:22:23

标签: mysql join group-by timestamp

有没有办法在MySQL中加入两个表,并为表中的每个不同的时间戳汇总第二个表中的元素?

所以这是我的表结构:

MySQL Workbench Structure

以下是一些数据示例:

设备表:

id  userId  time            mac           upload download deltaUpload deltaDownload
1   1   2008-01-01 00:00:01 00:00:00:00:01  0       0         100     1000
2   1   2008-01-01 00:00:01 00:00:00:00:02  0       0         400     4000
3   1   2008-01-01 00:00:01 00:00:00:00:03  0       0         0       500
4   2   2008-01-01 00:00:01 10:00:00:00:00  0       0         1000    5000
5   2   2008-01-01 00:00:01 20:00:00:00:00  0       0         4000    5000
6   1   2008-01-01 00:10:01 00:00:00:00:01  100     1000      500     10000
7   1   2008-01-01 00:10:01 00:00:00:00:02  400     4000      10000   500
8   1   2008-01-01 00:10:01 00:00:00:00:03  0       500       5000    5000
9   2   2008-01-01 00:10:01 10:00:00:00:00  1000    5000      500     10000
10  2   2008-01-01 00:10:01 20:00:00:00:00  4000    5000      10000   20000

用户表:

id  username
1   SomeUsername
2   SomeOtherUser

基本上我想要知道的是一个行集,每个时间戳都有一个条目(在这种情况下每10分钟一次),其中包含用户所有MAC地址的(delta)流量之和。

此表和userid = 1

的用户的示例结果
username         time                  upload  download
SomeUsername    2008-01-01 00:00:01     500     5500
SomeUsername    2008-01-01 00:10:01     15500   15500

这就是我对此查询的了解程度

SELECT 
    `users`.`username` AS 'username',
    `devices`.`time` AS 'time',
    `devices`.`deltaUpload` AS 'upload',
    `devices`.`deltaDownload` AS 'download'
FROM
    `devices`
        LEFT JOIN
    `users` ON (`users`.`id` = `devices`.`userId`)
GROUP BY`devices`.`time`;

我似乎只得到垃圾/没有结果

1 个答案:

答案 0 :(得分:0)

您的查询看起来不错,但您没有使用SUM

试试这个:

SELECT 
    `users`.`username` AS 'username',
    `devices`.`time` AS 'time',
    SUM(`devices`.`deltaUpload`) AS 'upload',
    SUM(`devices`.`deltaDownload`) AS 'download'
FROM
 `devices`
    LEFT JOIN
 `users` ON (`users`.`id` = `devices`.`userId`)
GROUP BY `users`.`username`, `devices`.`time`;