依靠mysql GROUP BY

时间:2015-02-17 00:15:09

标签: mysql count group-by

我想使用以下两个(简化)表格计算每个用户访问我网站的唯一天数:

Table: Users
+--------------+------------------+
| Field        | Type             |
+--------------+------------------+
| userid       | int(10)          |
| firstname    | varchar(50)      |
| lastname     | varchar(50)      |
+--------------+------------------+

Table: Visitors
+--------------+------------------+
| Field        | Type             |
+--------------+------------------+
| visitorid    | int(10)          |
| userid       | int(10)          |
| visitdate    | timestamp        |
+--------------+------------------+

首先,我按DATE(visitdate)分组,按日期对记录进行分组。 然后,我按userid分组,并对每个用户访问过的天数进行分组。

我对此的质询是:

SELECT count(userid) as count, userid, firstname, lastname FROM 
    (SELECT users.userid, firstname, lastname, DATE(`visitdate`) AS dateonly FROM 
    visitors JOIN users ON visitors.userid = users.userid 
    GROUP BY DATE(`visitdate`)) b 
GROUP BY userid ORDER BY count DESC

然而,这会给出一个不正确的计数,当我只是添加一个WHERE子句来限制用户ID时,会对此进行验证。以下查询为单个用户提供了正确的计数。

SELECT count(userid) as count, userid, firstname, lastname FROM 
    (SELECT users.userid, firstname, lastname, DATE(`visitdate`) AS dateonly FROM 
    visitors JOIN users ON visitors.userid = users.userid 
    WHERE users.userid = 167
    GROUP BY DATE(`visitdate`)) b 
GROUP BY userid ORDER BY count DESC

显然我错了 - 任何帮助都会受到赞赏。感谢。

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,我认为这就是你想要的:

SELECT u.userid, u.firstname, u.lastname, COUNT(DISTINCT CAST(v.visitdate AS DATE)) AS visits
FROM users u
LEFT JOIN visitors v ON v.userid = u.userid 
GROUP BY u.userid, u.firstname, u.lastname

这将显示每个用户的不同访问日期的用户ID,名字,姓氏和计数(如果没有访问则为0,因为它使用左连接来包含缺少访问者表中项目的用户)。