使用PHP将时间戳与MYSQL中的日期匹配

时间:2014-01-23 07:07:32

标签: mysql sql date select group-by

我有一张桌子

id user     Visitor timestamp
13 username abc     2014-01-16 15:01:44

我必须按日期(不是时间戳)“计算”过去七天“用户”的总访问者数量

SELECT count(*) from tableA WHERE user=username GROUPBY __How to do it__ LIMIT for last seven day from today.

如果有任何一天没有访客,那么就不会有行,所以它应该显示为0。

什么是正确的QUERY?

3 个答案:

答案 0 :(得分:6)

不需要GROUP BY结果集,您需要计算一周的访问次数(使用未指定的用户)。试试这个:

SELECT
    COUNT(*)
FROM
    `table`
WHERE
    `timestamp` >= (NOW() - INTERVAL 7 DAY);

如果您需要跟踪指定用户的访问次数,请尝试以下操作:

SELECT
    DATE(`timestamp`) as `date`,
    COUNT(*) as `count`
FROM
    `table`
WHERE
    (`timestamp` >= (NOW() - INTERVAL 7 DAY))
    AND
    (`user` = 'username')
GROUP BY
    `date`;

MySQL DATE() function reference

答案 1 :(得分:3)

试试这个:

SELECT DATE(a.timestamp), COUNT(*) 
FROM tableA a 
WHERE a.user='username' AND DATEDIFF(NOW(), DATE(a.timestamp)) <= 7
GROUP BY DATE(a.timestamp);

答案 2 :(得分:0)

我认为这是有效的:)

SELECT Count(*) 
from table A 
WHERE user = username AND DATEDIFF(NOW(),timestamp)<=7