在Laravel中查询多种条件的数据库的有效方法

时间:2019-12-29 04:17:31

标签: laravel query-builder multiple-conditions

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

$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();

1 个答案:

答案 0 :(得分:0)

查看您的查询代码后,我发现两个查询条件相同,而您只想获取最小low_usd记录,

我认为您可以只使用多重条件和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 上添加索引