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

OM *_*ity 1 php database time date

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

Today
Week
Month
Year
Run Code Online (Sandbox Code Playgroud)

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

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

lqe*_*qez 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";
Run Code Online (Sandbox Code Playgroud)

在查询中

# 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";
Run Code Online (Sandbox Code Playgroud)