简单的口才查询,执行时间太长

时间:2018-11-16 04:22:25

标签: mysql sql laravel eloquent

我有2个查询。即使第一个比较复杂并且提取更多的数据,它也只需要154毫秒即可执行,而第二个则需要1.76 s来执行。

首先(快速执行):

$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. 您对减少加载时间有任何想法吗?

3 个答案:

答案 0 :(得分:1)

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

这是第一个查询:

$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 :(得分:1)

如@Nikolas所说,从select(DB::raw..更改为selectRaw(...将有助于提高速度。

要检查的另一件事是在表的主要列上建立索引。

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

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

在表的关键列上具有索引可以大大提高查询速度

文档在此处提供有关通过迁移添加索引的详细信息:

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

答案 2 :(得分:1)

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

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

我已经通过使用一些“解决方法”解决了这个问题。由于每种可用货币的汇率每天都在变化,因此我只获得最大的currency_rate_batch_id,并获取与此ID相关联的所有货币(使我能够快速获取所有不同的货币)。

但是,我将应用索引编制(如@Josh所建议),并避免在整个项目中重复查询(如@Nicolas所建议)。

相关问题