MySQL之SQL语句的简单优化

本文介绍了SQL查询中的10个优化技巧,包括用exists代替in、避免前导模糊查询导致索引失效、正确使用负向查询和默认值、理解复合索引的最左前缀原则、合理使用limit、防止数据库自动类型转换、避免函数操作和or连接,以及表达式操作对索引的影响。
摘要由CSDN通过智能技术生成

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

总结一些SQL优化的内容。


1.用 exists 代替 in :

select num from a where num in(select num from b) 

用下面的语句替换:

select num from a where exists(select 1 from b where num=a.num) 

2.前导模糊查询会使索引失效:

select name from user where name like '%zhangsan'

非前导则不会使索引失效:

select name from user where name like 'zhangsan%'

3.负向查询不能使用索引

select name from user where id not in (1,3,4);

应该修改为:

select name from user where id in (2,5,6);

4.字段的默认值不要为 null

这样会带来和预期不一致的查询结果

5.复合索引的最左前缀问题

如果a,b两个字段建立了符合索引,这三种都是可以命中索引的

select a from T where a='aaa' and b='bbb'
select a from T where b ='bbb' and a='aaa'
select a from T where a='aaa' //虽然没满足最左前缀,但是MySQL会自动优化

以下则不生效:

select username from user where b ='bbb'

6.如果限定返回数据的数量

利用limit来停止数据库游标移动,提高效率

select name from user where username='zhangsan' limit 1

7.不要让数据库帮我们做类型转换

select name from user where telno=1383838438

改为:

select name from user where telno=1383838438

8. 尽量避免在where子句中对字段进行函数操作

这将导致引擎放弃使用索引而进行全表扫描。

select id from t where substring(name,1,3)='abc'--name以abc开头的id 

select id from t where datediff(day,createdate,'2005-11-30')=0--'2005-11-30'生成的id 

应改为:

select id from t where name like 'abc%' 
select id from t where createdate>='2005-11-30' and createdate<'2005-12-1' 

9.应尽量避免在 where 子句中使用 or 来连接条件

会导致引擎放弃使用索引而进行全表扫描

select id from t where num=10 or num=20 

可以改成:

select id from t where num=10 
union all 
select id from t where num=20 

10.应尽量避免在 where 子句中对字段进行表达式操作,

这将导致引擎放弃使用索引而进行全表扫描。

select id from t where num/2=100 

应改为:

select id from t where num=100*2 
  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值