从SQL中的时间戳,从今天,昨天,本周,本月和两个日期之间选择记录php mysql

2021-12-19 00:00:00 date select filter mysql

希望这是一个简单的解决方案,但我正在尝试过滤以下数据:-

Hopefully, it's an easy solution, but I am trying to filter the data for the following:-

  • 今天
  • 昨天
  • 本周
  • 本月
  • 在两个日期之间.

我从数据库中得到的日期基本上是一个时间戳.

The date I get from the database is basically a timestamp.

这是我试过的:-

  • 今天

SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 DAY)

  • 昨天

  • Yesterday

    SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 7 DAYS)
    

  • ...

    这真的行不通.

    有什么想法吗?

    推荐答案

    如果您仅按日期选择,则根据 CURDATE(仅返回日期)而不是 NOW 进行计算(返回日期和时间).这些示例将捕获一天范围内的所有时间:

    If you're selecting by date only, base your calculations on CURDATE (which returns date only) rather than NOW (which returns date and time). These examples will catch all times within the day ranges:

    • 今天:WHERE timestamp >= CURDATE()
    • 昨天:WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND timestamp <CURDATE()
    • 本月:WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY)
    • 在 2013 年 6 月 3 日和 2013 年 6 月 7 日这两个日期之间(注意如何将结束日期指定为 6 月 8 日,而不是 6 月 7 日):WHERE timestamp >='2013-06-03' AND timestamp <;'2013-06-08'

    本周"取决于您开始一周的哪一天;我会把它留给你.您可以使用 DAYOFWEEK 函数将 CURDATE() 调整到适当的范围.

    The "this week" depends on which day you start your week; I'll leave that to you. You can use the DAYOFWEEK function to tweak CURDATE() to the proper ranges.

    附录:OP 的列类型是 INTEGER,存储 UNIX 时间戳,我的回答假设列类型是 TIMESTAMP.以下是如何使用 UNIX 时间戳值执行所有相同的操作,并且如果该列被编入索引仍然保持优化(如果 TIMESTAMP 列被编入索引,上面的答案将执行)...

    Addendum: OP's column type was INTEGER, storing a UNIX timestamp, and my answer assumed the column type was TIMESTAMP. Here's how to do all the same things with a UNIX timestamp value and still maintain optimization if the column is indexed (as the answers above will do if the TIMESTAMP column is indexed)...

    基本上,解决方案是将开始和/或结束日期包装在 UNIX_TIMESTAMP 函数:

    Basically, the solution is to just wrap the beginning and/or ending dates in the UNIX_TIMESTAMP function:

    • 今天:WHERE timestamp >= UNIX_TIMESTAMP(CURDATE())
    • 昨天:WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 DAY)) AND timestamp <UNIX_TIMESTAMP(CURDATE())
    • 本月:WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY))
    • 在 2013 年 6 月 3 日和 2013 年 6 月 7 日这两个日期之间(注意如何将结束日期指定为 6 月 8 日,而不是 6 月 7 日):WHERE timestamp >= UNIX_TIMESTAMP('2013-06-03') AND时间戳

    相关文章