过去 24 小时内最流行的 PHP MySQL 查询
假设我想获得过去 24 小时内点赞最多的 10 条记录。这是我到目前为止所得到的:
$date = date("o-m-d");
$query = "SELECT date_created,COUNT(to),from,to FROM likes WHERE date_created LIKE '$date%' GROUP BY to ORDER BY COUNT(to) DESC LIMIT 10";
问题是,它只会从那天起获得最多的点赞,无论距离那一天有多远。过去 24 小时内它没有获得最多点赞。
点赞的结构:来自 |至 |创建日期 | id
日期采用标准 ISO 时间 - 例如 2010-07-14T00:35:31-04:00。直接来自 PHP 参考: date("c");
Say I want to get ten records with the MOST likes in the last 24 hours. Here's what I have so far:
$date = date("o-m-d");
$query = "SELECT date_created,COUNT(to),from,to FROM likes WHERE date_created LIKE '$date%' GROUP BY to ORDER BY COUNT(to) DESC LIMIT 10";
The problem with that is that it only gets the most liked from THAT DAY, no matter how far into that day it is. It doesn't get the most liked from the last 24 hours.
structure for likes: from | to | date_created | id
dates are in standard ISO time - example 2010-07-14T00:35:31-04:00. Come straight from the PHP reference: date("c");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的 date_created 字段是日期时间或时间戳字段类型,您可以在 where 子句中使用 DATE_SUB ,如下所示;
If your date_created field is a datetime or timestamp field type, you can use DATE_SUB in your where clause as follows;
因此,首先应该将 date_created 定义为带有
默认当前时间戳
的时间戳。如果表中也有 date_modified,则 date_modified 将具有更新当前时间戳
,并且您可以使用创建的日期定义为时间戳,并使用此触发器来更新它现在我们有了时间戳,您可以轻松地将一些 mysql 日期函数应用于该列。
http://dev.mysql.com/ doc/refman/5.1/en/date-and-time-functions.html
我将把要做的事情留给读者作为练习,除非你说“非常请”并希望我给出确切的语法。
So first off date_created should be defined as a timestamp with on
default current timestamp
. If you have a date_modified in the table as well then date_modified would haveon update current timestamp
and you can defined with date created as a timestamp and this trigger to update itNow that we have a timestamp you can easily apply some of the mysql date functions to the column.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
I'll leave what to do as an exercise for the reader, unless you say pretty please and want me to give the exact syntax.
您应该使用日期/时间函数,而不是 LIKE。
You should be using date/time functions, instead of LIKE.