测距日期中的SQL WHERE子句计算

时间:2011-08-25 10:33:51

标签: php database date time

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

Today
Week
Month
Year

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

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

3 个答案:

答案 0 :(得分:5)

当您将日期时间存储为纪元时间戳格式时,我认为使用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";

答案 1 :(得分:0)

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

EG。要获得一周或更新的行,您可以执行以下操作:

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

答案 2 :(得分:0)

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

相关问题