在 laravel 中使用多个条件查询数据库的有效方法

Efficient way to query database with multiple conditions in 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();

看了你的查询代码,我发现这两个查询条件是一样的,你只想得到min 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

上添加索引