简单的Eloquent查询执行时间过长



我有两个查询。尽管第一个更复杂,提取的数据更多,但执行只需154毫秒,而第二个需要1.76秒。

第一(执行速度快(:

$offers = Offer::select(DB::raw('tbl_offer.offer_id as sys_id, 
tbl_offer.offer_name, 
tbl_offer.preview_url, 
COALESCE(tbl_offer.is_allow_website_links, 
false) as is_allow_website_links, 
tbl_offer.is_require_approval, 
tbl_relationship.fk_relationship_status_id, 
tbl_offer.is_private,
tbl_offer.currency'))
->leftJoin('tbl_relationship', function ($q) use ($affiliateId) {
$q->on('tbl_offer.offer_id', '=', 'tbl_relationship.fk_offer_id')
->where('tbl_relationship.fk_affiliate_id', '=', $affiliateId);})
->whereIn('fk_offer_status_id', [ 18, 19 ])
->where('is_display', 1)
->where('tbl_offer.is_trd_deleted', 0)
->orderBy('offer_name')
->get();

第二(执行缓慢(:

$currencies = Currency::select(DB::raw('DISTINCT currency_code_from AS currency'))
->where('sys_name', 'openexchangerates')
->orderBy('currency')
->get();   
  1. 可能是什么问题
  2. 你对如何减少装载时间有什么想法吗

首先,您要将两个查询合并为一个查询。

这是第一个查询:

$currencies = Currency::where('sys_name', 'openexchangerates')
->orderBy('currency')
->get();  

这是另一个:

DB::raw('DISTINCT currency_code_from AS currency')

为了将两个查询合并为一个查询,您应该使用以下内容:

$currencies = Currency::selectRaw('DISTINCT currency_code_from AS currency')
->where('sys_name', 'openexchangerates')
->orderBy('currency')
->get();   

我希望这种方式能减少执行时间。

只需留下这个答案,因为它可能对那些已经尝试应用索引和查询优化但未能显著减少时间的人有用。

我已经设法将查询加载时间从1.76秒减少到0.127秒。

我用一些"绕着走"的方法解决了这个问题。由于每一种可用货币的汇率每天都在变化,我只是得到了最大的currency_rate_batch_id,并得到了与该id相关的所有货币(使我能够快速获得所有不同的货币(。

然而,我将应用索引(正如@Josh所建议的(,并在整个项目中避免双重查询(正如@Nicolas所建议的那样(。

As@Nikolas表示,从select(DB::raw..更改为selectRaw(...将有助于提高速度。

您需要检查的另一件事是对表的主要列进行索引。

我假设您正在使用Mysql,因此请查看以下关于索引的文档

https://dev.mysql.com/doc/refman/5.5/en/optimization-indexes.html

在表的关键列上设置索引会对的查询速度产生很大影响

Docs在这里有关于通过迁移添加索引的详细信息:

https://laravel.com/docs/5.5/migrations#indexes

最新更新