在Laravel中查询多个条件的有效方法

问题描述 投票:0回答:1

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

$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();
laravel query-builder multiple-conditions
1个回答
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上添加索引

© www.soinside.com 2019 - 2024. All rights reserved.