提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
提示:这里可以添加本文要记录的大概内容:
总结一些SQL优化的内容。
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)
select name from user where name like '%zhangsan'
非前导则不会使索引失效:
select name from user where name like 'zhangsan%'
select name from user where id not in (1,3,4);
应该修改为:
select name from user where id in (2,5,6);
这样会带来和预期不一致的查询结果
如果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'
利用limit来停止数据库游标移动,提高效率
select name from user where username='zhangsan' limit 1
select name from user where telno=1383838438
改为:
select name from user where telno=“1383838438”
这将导致引擎放弃使用索引而进行全表扫描。
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'
会导致引擎放弃使用索引而进行全表扫描
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
这将导致引擎放弃使用索引而进行全表扫描。
select id from t where num/2=100
应改为:
select id from t where num=100*2