当前位置:网站首页>MySQL优化之强制索引的使用
MySQL优化之强制索引的使用
2022-07-22 09:03:00 【蹦跶哒的王小哲】
问题描述:
-- 根据类型(type)以及类型id(type_id)查询所有的在职人员(status=1)的id、姓名、岗位(post_name)以及部门id
SELECT
u.id,
realname,
s.title AS post_name,
new_groupid
FROM
crm_user u
LEFT JOIN crm_station s ON u.post = s.id
WHERE
type = 0
AND type_id = 0
AND u.`status` = 1
(1)在user表中对type字段添加索引;
(2)首先使用explain来查看一下SQL性能如下:
通过结果可以看出,虽然对type字段已经建立了索引,但是这个索引好像并没有起到作用,那么究竟是为什么呢?因为 type字段值的类型不多,就好比性别字段,除了1就是0,这种情况下影响结果集巨大,就会全表扫描,这种情况全表扫描还要快于利用索引。那如何继续使用索引呢?
解决方案:
SELECT
u.id,
realname,
s.title AS post_name,
new_groupid
FROM
crm_user u FORCE INDEX(type)
LEFT JOIN crm_station s ON u.post = s.id
WHERE
type = 0
AND type_id = 0
AND u.`status` = 1
(1)对type字段使用强制索引 FORCE INDEX(字段名称);
(2)再次使用explain来查看一下SQL性能如下:
边栏推荐
猜你喜欢
double类型不能进行精确计算的问题
C语言中continue的理解(fishing_1)
"Review of software engineering in Wuhan University of technology" Chapter 7 | software testing
互斥锁和信号量
第十二讲 MySQL之高可用组件MHA
Qt|编辑框的使用总结
Female guest registration
Microsoft SQL Server数据库语言及功能使用(十二)
Yunyuanyuan (10) | introduction to kubernetes in kubernetes
"Review of software engineering in Wuhan University of technology" Chapter 6 | coding specification
随机推荐
Mutexes and semaphores
力扣解法汇总735-行星碰撞
力扣解法汇总324-摆动排序 II
What level do programmers need to reach to get 20K monthly salary without pressure?
力扣解法汇总241-为运算表达式设计优先级
SQL设计教学管理库
「武汉理工大学 软件工程复习」第六章 | 编码规范
GeoWebCache发布ArcGIS切片数据
原型对象
力扣解法汇总814-二叉树剪枝
关于STemwin中,外部实体按键操作Spinbox控件(fishing_2)
【How To 系列】好友裂变平台搭建
DistSQL 深度解析:打造动态化的分布式数据库
Understand relevant concepts of prosody. XMPP, jabber, bosh, etc
Simplify the complexity and talk about the abstraction of replication state machine system architecture
水博士
Microsoft SQL Server数据库语言及功能使用(十二)
How to build a clear and understandable data Kanban?
creating vlan over openstack (by quqi99)
Ssl/tls protocol attack detection method based on stream spectrum theory