laravel - 在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();
解决方案
看了你的查询代码,我发现两个查询条件是一样的,你只想得到最小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();
在此之后,如果你想让这个查询更有效率,
您需要在, ,上添加索引slug
low_usd
created_time
推荐阅读
- node.js - 从 atomicassets (wax.atomichub.io) 获取数据时,使用 discord.js 的 Node.js GET 错误
- c# - 使用 asParallel vs async function() 对集合进行迭代
- swiftui - SwiftUI App Lifecycle,为 GoogleSignIn 呈现 ViewController
- mongoose - 使用猫鼬崩溃在 NestJS 中实例化新文档
- c++ - Arduino 伺服对象在我自己的库中不起作用
- python - 如何在python中将字符串变量打印为f字符串
- javascript - 从javascript中生成的数据中获取最后一个数组
- c - “free(): double free 在 tcache 2 中检测到”是什么意思?
- javascript - 如何编写猫鼬更新来更新整个文档,包括各种子文档
- go - 将 go 文件放在模块路径上是一个好习惯吗?