SQL WHERE子句在Date中计算range


SQL WHERE clause calculation in Date for Ranging

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

Today
Week
Month
Year

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

现在我需要按照上面提到的标签从我的表中获取记录,我怎么能做到这一点?

当你以epoch时间戳格式存储datetime时,我认为使用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";

您可以使用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函数来处理日期:

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列中

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