【MySql】——优化

使数据库放弃索引而使用全表扫描的查询

1.null值判断
select id from t where num is null
改正:
尽量少的使用null值,空值可以用0替代
2.!=或<>操作符
3.or操作符
select id from t where num=10 or Name = 'admin'
改正:
select id from t where num = 10
union all
select id from t where Name = 'admin'
4.in和not in操作符
select id from t where num in(1,2,3)
改正:
①对于连续的数值,能用between就不用in,select id from t where num between 1 and 3
②用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)
5.like
select id from t where name like '%abc%'
改正:
可以考虑全文检索
6.where子句上使用参数
select id from t where num = @num
改正:(强制使用索引查询)
select id from t with(index(索引名)) where num = @num
7.where子句中对字段进行表达式操作
select id from t where num/2 = 100
改正:
select id from t where num = 100*2
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.不带任何条件的count
select count(*) from table;


操作优化

1.update语句,如果只更改少量字段,不要update全部字段
2.对于多张大数据量的表JOIN,要先分页再JOIN,否则逻辑读会很高,性能很差。
3.尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连 接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。
4.尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。
5.任何地方都不要使用 select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。
6.尽量使用表变量来代替临时表。如果表变量包含大量数据,请注意索引非常有限(只有主键索引)。
7.在新建临时表时,如果一次性插入数据量很大,那么可以使用 select into 代替 create table,避免造成大量 log ,以提高速度;如果数据量不大,为了缓和系统表的资源,应先create table,然后insert。
8.如果使用到了临时表,在存储过程的最后务必将所有的临时表显式删除,先 truncate table ,然后 drop table ,这样可以避免系统表的较长时间锁定。
9.尽量避免大事务操作,提高系统并发能力。

猜你喜欢

转载自blog.csdn.net/tengliu6/article/details/80870154
今日推荐