过去 24 小时内最流行的 PHP MySQL 查询

发布于 2024-09-10 10:27:51 字数 438 浏览 7 评论 0原文

假设我想获得过去 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

跨年 2024-09-17 10:27:51
WHERE date_created > DATE_SUB( NOW(), INTERVAL 24 HOUR)
WHERE date_created > DATE_SUB( NOW(), INTERVAL 24 HOUR)
征棹 2024-09-17 10:27:51

如果您的 date_created 字段是日期时间或时间戳字段类型,您可以在 where 子句中使用 DATE_SUB ,如下所示;


WHERE date_created > DATE_SUB(NOW(), INTERVAL 24 HOUR)

If your date_created field is a datetime or timestamp field type, you can use DATE_SUB in your where clause as follows;


WHERE date_created > DATE_SUB(NOW(), INTERVAL 24 HOUR)

风月客 2024-09-17 10:27:51

因此,首先应该将 date_created 定义为带有默认当前时间戳的时间戳。如果表中也有 date_modified,则 date_modified 将具有更新当前时间戳,并且您可以使用创建的日期定义为时间戳,并使用此触发器来更新它

CREATE TRIGGER likes_date_entered
BEFORE INSERT ON likes
FOR EACH ROW SET NEW.date_created = NOW()

现在我们有了时间戳,您可以轻松地将一些 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 have on update current timestamp and you can defined with date created as a timestamp and this trigger to update it

CREATE TRIGGER likes_date_entered
BEFORE INSERT ON likes
FOR EACH ROW SET NEW.date_created = NOW()

Now 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.

独享拥抱 2024-09-17 10:27:51

您应该使用日期/时间函数,而不是 LIKE。

WHERE date_created >= (NOW() - INTERVAL 24 HOUR)

You should be using date/time functions, instead of LIKE.

WHERE date_created >= (NOW() - INTERVAL 24 HOUR)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文