MySql group by和include

时间:2014-04-19 06:39:46

标签: mysql

我有这两张桌子:

Table members
| id | name    |
----------------
| 01 | John    |
| 02 | Michael |
| 03 | Richard |

Table payments
| id  | eur  | name    | date       |
-------------------------------------
| 238 | 9.95 | John    | 1323377751 |
| 233 | 9.95 | Michael | 1397864609 |
| 220 | 9.95 | Michael | 1397852739 |
| 215 | 9.95 | John    | 1397852719 |
|   2 | 9.95 | Richard | 1323377751 | // This payment was made more than 24h ago

贝娄是我的疑问:

select id, m.name, sum(eur) as total 
from mambers as m
left join payments as p
on m.name = p.name
where p.date >= unix_timestamp(current_timestamp - interval 24 hour)
group by m.name

并且返回:

| John    | 19.90 |
| Michael | 19.90 |  

但我需要在过去的24小时内同时包含没有付款的会员:

| John    | 19.90 |
| Michael | 19.90 |
| Richard | 00.00 |

1 个答案:

答案 0 :(得分:1)

尝试查询时发生了两次错误。

  1. 表名mambers不存在。

  2. 不明确的列名id

  3. 请改为尝试:

    select m.id, m.name, IFNULL(sum(eur),'00.00') as total 
    from members as m
    left join payments as p
    on m.name = p.name and p.date >= unix_timestamp(current_timestamp - interval 24 hour)
    group by m.name
    

    结果:

    ID  NAME      TOTAL
    1   John      10
    2   Michael   20
    3   Richard   00.00
    

    请参阅SQL Fiddle中的结果。