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

Ade*_*ova 5 mysql sql laravel eloquent

我有 2 个查询。尽管第一个更复杂并且提取的数据更多,但执行时间仅为 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();
Run Code Online (Sandbox Code Playgroud)

第二个(执行缓慢):

$currencies = Currency::select(\DB::raw('DISTINCT currency_code_from AS currency'))
                 ->where('sys_name', 'openexchangerates')
                 ->orderBy('currency')
                 ->get();   
Run Code Online (Sandbox Code Playgroud)
  1. 可能是什么问题?
  2. 您对如何减少加载时间有任何想法吗?

Nik*_*vas 2

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

这是第一个查询:

$currencies = Currency::where('sys_name', 'openexchangerates')
            ->orderBy('currency')
            ->get();  
Run Code Online (Sandbox Code Playgroud)

这是另一个:

\DB::raw('DISTINCT currency_code_from AS currency')
Run Code Online (Sandbox Code Playgroud)

为了将两个查询合而为一,您应该使用以下命令:

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

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