laravel查詢語句指定索引(mysql強制索引)


1.直接上圖,如下是查詢的原生sql:

 1 EXPLAIN SELECT  2     `erp_agents`.`company_id`  3 FROM  4 `erp_agents` FORCE INDEX (`test`)  5 LEFT JOIN `erp_positions` ON `erp_positions`.`id` = `erp_agents`.`position_id`  6 WHERE  7     `erp_agents`.`status` IN ('預離職', '正常')  8 AND `worked_at` <= '2018-09-30 23:59:59'
 9 AND `is_suppose` = '0'
10 AND `erp_agents`.`company_id` = '2'
11 AND `erp_agents`.`deleted_at` IS NULL
12 AND `erp_agents`.`company_id` = '2'

 

2.在laravel的代碼里面需要這樣寫,如下圖:

在這里用when方法來判斷此索引是否存在,日過不存在的話就不用這個索引,不然會報錯,避免有人誤刪索引后,導致系統報錯。

此處強制索引的語句是:

->from(DB::raw('`erp_agents` FORCE INDEX (`test`)'))
$agents = Agent::where($whereType) ->when(hasIndex('Agent', 'test'),function ($q){ $q->from(DB::raw('`erp_agents` FORCE INDEX (`test`)')); }) ->when(request('position',false),function ($q){ $q->whereIn('position_id',request('position')); }) ->whereIn('agents.status', $validStatus) ->where('worked_at', '<=', $end) ->where('is_suppose', 0) ->addDomination('m.statistics-human-view') ->leftJoin('positions', 'positions.id', '=', 'agents.position_id') ->get(['worked_days', 'worked_at']);

 

over!

轉發請注明出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM