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

广告:宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取~~~

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

为什么需要强制索引?

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

mysql强制索引查询语句

select * from user where age = 26 force index(age); // 强制索引

select * from user where age = 26 use index(age); // 优先按照这种索引查找

/** * 检测某个表中是否存在某个索引 * @param $table * @param $index * @return bool * @author zhaohao * @date 2019-08-26 17:42 */if(!function_exists('hasIndex')) {    function hasIndex($table, $name)    {        $conn = IlluminateSupportFacadesSchema::getConnection();        $dbSchemaManager = $conn->getDoctrineSchemaManager();        $doctrineTable = $dbSchemaManager->listTableDetails($table);        return $doctrineTable->hasIndex($name);    }}

登录后复制在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']);

登录后复制

【相关推荐:最新的五个Laravel视频教程】

以上就是laravel学习记录之强制指定索引进行查询的详细内容,更多请关注9543建站博客其它相关文章!

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。

作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:看看PHP 7中怎么优化递归的!
下一篇:如何用PHP正则表达式验证邮件地址格式

发表评论

关闭广告
关闭广告