我想使用以下两个(简化的)表格来计算每个用户访问我的网站的唯一天数:
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
子句以限制用户标识时就可以验证该计数。以下查询为单个用户提供正确的计数。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
显然我错了-任何帮助将不胜感激。谢谢。
最佳答案
如果我正确理解您的问题,我想这就是您想要的:
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
这将为您显示每个用户的不同的访问日期的用户名,名字,姓氏和计数(如果没有访问,则为0,因为它使用左联接将游客表中缺少项目的用户包括在内)。
关于mysql - 依靠mysql GROUP BY,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28552618/