我有一个包含行的数据库:SearchTerm | userId |日期| historyId
我需要在userId = userid的最后24小时内每小时获取一些条目。
到目前为止,我有以下内容:
$stmt = $conn->prepare("SELECT historyId FROM webHistory WHERE date >= now() - INTERVAL 1 DAY GROUP BY HOUR(date) AND userId=?");
我现在有点陷入困境,我怎样才能获得每小时组的num_rows?我虽然使用count(*),但这是正确的方法,如果是这样我将如何去做呢?
最后,对于移动显示器,我需要每两个小时分组,这是否可能,因为我似乎只能在HOUR()上找到文档,可能是DATEPART()?
答案 0 :(得分:2)
您只需要count(*)
:
SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows
FROM webHistory
WHERE date >= now() - INTERVAL 1 DAY AND userId=?
GROUP BY HOUR(date);
userId
上的条件位于where
子句中。将hour(date)
包含在select
中是一种很好的形式,因此您知道给定计数所指的小时数。
编辑:
要获得今天的时间,小时可以做到:
SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows
FROM webHistory
WHERE date(date) = date(now()) AND userId=?
GROUP BY HOUR(date);
答案 1 :(得分:2)
按两小时的时段列出数据:
SELECT FLOOR(HOUR(date)/2) AS period,historyId FROM webHistory, COUNT(*) as num_rows
WHERE date >= now() - INTERVAL 1 DAY
GROUP BY date, period
答案 2 :(得分:2)
我们可以使用SQL BETWEEN运算符
SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows
FROM webHistory
WHERE date BETWEEN SUBDATE(date(now()),1) AND date(now())
AND userId=?
GROUP BY HOUR(date);