【问题标题】:Query the DB DATETIME column just by date仅按日期查询 DB DATETIME 列
【发布时间】:2015-06-10 18:10:22
【问题描述】:

我在数据库中有一个DATETIME 类型的列,格式为yyyy-mm-dd hh:mm:ss。尽管如此,作为信息,我只得到了日期(我不在乎时间)。那么我应该如何查询数据库以仅按日期搜索该列,即使该值同时包含日期和时间?

更新:

这是我尝试选择实体的 PHP 代码:

public static function getTripsWithDrivers($route_from = null, $route_to = null, $date = null)
{
   $trips = Trip::whereRouteFrom($route_from)->whereRouteTo($route_to)->whereStartDate($date);
   ...
}

【问题讨论】:

  • 最佳解决方案是BETWEEN date1 AND date2,其中date1 与时间00:00:00 一致,date2 与时间23:59:59 一致。这将使用字段上的索引,如果你有的话。函数DATE(date) 不会使用索引。

标签: php mysql datetime laravel laravel-4


【解决方案1】:

用户过滤如下:

WHERE "datetime column" like '2015-04-06%'

【讨论】:

    【解决方案2】:

    使用MySqldate函数:

    $trips = Trip::where(DB::raw('DATE(route_from)'), '=', $route_from)
                 ->where(DB::raw('DATE(route_to)'), '=', $route_to)
                 ->where(DB::raw('DATE(start_date)'), '=', $date)
    

    【讨论】:

    • 提示:这不会使用日期字段上使用的任何索引。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2013-01-18
    • 2021-08-13
    • 2020-08-25
    相关资源
    最近更新 更多