mysql在同一个表上组合不同的count()

时间:2017-12-02 22:41:17

标签: mysql

我的数据库拥有一个' lastOnline'用户登录时获取更新的timestamp变量。我想使用它来检索3个值

[The total amount of users][users online today][users online in the last hour].

我可以单独做每个陈述

SELECT count(u.id) AS usersTotal FROM user u

SELECT count(u.id) AS usersDay FROM user u
WHERE u.lastOnline >= now() - INTERVAL 1 DAY

SELECT count(u.id) AS usersHour FROM user u
WHERE u.lastOnline >= now() - INTERVAL 1 HOUR

但我无法将其中的3个加入/联合到一个查询中

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用:

SELECT count(u.id) AS usersTotal 
      ,SUM(u.lastOnline >= now() - INTERVAL 1 DAY)  AS usersDay
      ,SUM(u.lastOnline >= now() - INTERVAL 1 HOUR) AS usersHour
FROM user u;

工作原理:

u.lastOnline >= now() - INTERVAL 1 DAY返回true(1)或false(0)。