首页 > 解决方案 > 在laravel中查询具有多个条件的数据库的有效方法

问题描述

是否可以将其设为单个查询?

$yl_min = DB::connection($this->db2)->table('historical')
    ->where([['slug','=',$crypto_id],['low_usd','!=', null]])
    ->whereBetween('created_time',[$this->range_1y,$this->hislatest])
    ->min('low_usd');

$yl = DB::connection($this->db2)->table('historical')
    ->select('id','coin','low_usd','created_time','created_at')
    ->where([['slug','=',$crypto_id],['low_usd',$yl_min]])
    ->whereBetween('created_time',[$this->range_1y,$this->hislatest])
    ->first();

我试过这个但没有运气:

$yl = DB::connection($this->db2)->table('historical')
    ->select('id','coin','created_time','created_at',DB::raw('SELECT MIN(low_usd) as low_usd'))
    ->where([['slug','=',$crypto_id],['low_usd','!=', null]])
    ->whereBetween('created_time',[$this->range_1y,$this->hislatest])
    ->first();

标签: laravelquery-buildermultiple-conditions

解决方案


看了你的查询代码,我发现两个查询条件是一样的,你只想得到最小low_usd记录,

我认为您可以只使用多个条件 and ORDER BY low_usd ASC,然后采用第一个条件:

$yl = DB::connection($this->db2)->table('historical')
                ->where([['slug','=',$crypto_id],['low_usd','!=', null]])
                ->whereBetween('created_time',[$this->range_1y,$this->hislatest])
                ->orderBy('low_usd','asc')
                ->select('id','coin','low_usd','created_time','created_at')
                ->first();

在此之后,如果你想让这个查询更有效率,

您需要在, ,上添加索引sluglow_usdcreated_time


推荐阅读