Laravel学习记录之强制指定索引进行查询

 4292

本文带大家学习Laravel强制指定索引进行查询,希望对大家有所帮助。


为什么需要强制索引?

数据库没有使用我们设想的索引进行sql查询,导致查询特别慢。


mysql强制索引查询语句

  1. select * from user where age = 26 force index(age); // 强制索引
  2. select * from user where age = 26 use index(age); // 优先按照这种索引查找
  1. /**
  2.  * 检测某个表中是否存在某个索引
  3.  * @param $table
  4.  * @param $index
  5.  * @return bool
  6.  * @author zhaohao
  7.  * @date 2019-08-26 17:42
  8.  */
  9. if(!function_exists('hasIndex')) {
  10.     function hasIndex($table, $name)
  11.     {
  12.         $conn = IlluminateSupportFacadesSchema::getConnection();
  13.         $dbSchemaManager = $conn->getDoctrineSchemaManager();
  14.         $doctrineTable = $dbSchemaManager->listTableDetails($table);
  15.         return $doctrineTable->hasIndex($name);
  16.     }
  17. }


在laravel的代码里面需要这样写:

在这里用when方法来判断此索引是否存在,日过不存在的话就不用这个索引,不然会报错,避免有人误删索引后,导致系统报错。

此处强制索引的语句是:

  1. ->from(DB::raw('`erp_agents` FORCE INDEX (`test`)'))

例如:

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


本文网址:https://www.zztuku.com/index.php/detail-9852.html
站长图库 - Laravel学习记录之强制指定索引进行查询
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐