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!

转发请注明出处!

posted @ 2018-10-10 17:34  李傲强  阅读(3816)  评论(0编辑  收藏  举报