【问题标题】:SQL WHERE clause calculation in Date for Ranging测距日期中的 SQL WHERE 子句计算
【发布时间】:2011-08-25 10:33:50
【问题描述】:

我有一个项目,其中模块需要使用一组特定条件显示数据列表:

Today
Week
Month
Year

数据库表包含一个数据类型为 BIGINT(10) 的日期字段,我们通过 PHP 代码将 time() 函数值插入其中。其中插入一些值,例如 1311144077,

现在我需要根据上面提到的标签从我的表中获取记录,我该怎么做?

【问题讨论】:

  • 您可以使用 PHP 的 date()/strtotime() 函数轻松计算这一天、一周等的开始时间戳,例如这一天的开始时间:strtotime(date("Y-m-d")) 等.

标签: php database date time


【解决方案1】:

虽然您以纪元时间戳格式存储日期时间,但我认为使用 MySQL 日期/时间函数的解决方案可能会非常慢。所以,我建议像下面的代码一样使用时间戳本身。

使用示例

$t = time();

# today
echo date('Y-m-d H:i:s', strtotime('today', $t))."\n";
echo date('Y-m-d H:i:s', strtotime('tomorrow', $t))."\n";

# this week  
echo date('Y-m-d H:i:s', strtotime('-1 sunday', $t))."\n";
echo date('Y-m-d H:i:s', strtotime('sunday', $t))."\n";

# this month  
echo date('Y-m-d H:i:s', strtotime(date('Y-m-01 00:00:00', $t)))."\n";
echo date('Y-m-d H:i:s', strtotime(date('Y-m-01 00:00:00', strtotime('next month', $t))))."\n";

# this year
echo date('Y-m-d H:i:s', strtotime(date('Y-01-01 00:00:00', $t)))."\n";
echo date('Y-m-d H:i:s', strtotime(date('Y-01-01 00:00:00', strtotime('next year', $t))))."\n";

查询中

# this year
$start_of_year = strtotime(date('Y-01-01 00:00:00', $t));
$end_of_year = strtotime(date('Y-01-01 00:00:00', strtotime('next year', $t)));
$query = "SELECT * FROM sometable WHERE somecolumn >= $start_of_year AND somecolumn < $end_of_year";

【讨论】:

  • 感谢 Iqez 的 Quik 简单的描述性回复
【解决方案2】:

您可以使用strtotime() 函数获取下限时间戳,例如。 strtotime('-1 week'),然后在数据库中查询所有日期字段值大于该值的记录。

例如。要获得一周前或更新的行,您可以这样做:

$ts = strtotime('-1 week');
// or $ts = strtotime('date'); where date can be a date in Y-m-d format
mysql_query("SELECT * FROM table WHERE your_bigint_column >= $ts");

如果需要按月分组,可以使用MySQL functions for processing dates

SELECT WEEK(FROM_UNIXTIME(your_bigint_column)) AS no_of_week, count(*)
FROM table
GROUP BY WEEK(FROM_UNIXTIME(your_bigint_column))

在一个不相关的注释中 - BIGINT(10) 是一种过度杀伤,time() 的结果可以安全地存储在一个 INT 列中。

【讨论】:

  • 我希望现在更好?如果没有,请详细说明您要达到的目标。
【解决方案3】:

此命令会将保存在数据库 date("j F,Y", "1222041600") 中的时间戳更改为 1-6-1987,然后您将拥有月日和年,在此您也可以计算周。更多详细信息请参见日期的 php 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 2019-07-15
    • 2023-03-04
    • 2012-06-24
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多