1、关于字段默认值
要学适当的学会为字段加默认值,在where子句中 where count is null 是会让搜索引擎进行全表搜索而放弃使用索引,如果采用where count =0 则会提高效率
2、尽量不要在where 子句中使用!=或者<> 优化器无法通过索引来确定将要命中的行数而进行全表扫描
3、尽量避免使用or关键字,也会使搜索引擎放弃使用索引而进行全表扫描
可以使用union all 进行查询 例如 select * from name where id=1 or id=2
改为 select * from name where id=1 union all select * from name where id =2
4、in 和not in 也要慎用 因为这样也会使引擎放弃索引进行全表查找
若果是对连续的数值进行查找 例如 select * from t where id in (1,2,3)
则可以修改为 select * from t where id between 1 and 3
5、尽量不要在索引过的字符数据中使用非打头字母搜索,这样也会放弃使用索引
例如 select * from t where name like ‘%L%‘
select * from t where substring(name,1,2) =‘L‘
使用 select * from t where name like ‘L%‘ 可以用索引
6、可以强制使用索引来进行优化
在where 子句中使用参数化查询,也会导致全表扫描,sql只有在运行时才会进行局部变量的解析,但是诸如索引之类的优化程序不能推迟到运行时必须在编译时进行选择
例如 select * from t where num =@num
可以进行优化 select * from t with (index(索引名)) where num =@num
7、任何对列的操作都会引起表扫描,它包括数据库函数、计算表达式,查询时要尽可能移动到等号右侧进行,不要在=左边进行函数、算术运算或者其他计算表达式,这样索引可能无法正确使用
8、要注意的是。如果使用索引字段作为查询条件时,如果创建的是符合索引,一定要使用符合索引的第一个字段作为条件才会起到作用,并且尽可能让字段顺序和索引顺序一致
9、善用exist
才查询是否存在某条数据时,用exist代替查询count
select num from a where num in(select num from b)
上面这个语句可以用
select num from a where exist (select 1 from b where num=a.num)
代替 因为后面的这个语句没有使用in等类似会产生扫描表的关键字。
10、大事务的操作要谨慎使用,提高系统的并发能力
11、避免使用不兼容的数据类型,例如float和int,char和varchar,binary和varbinary是不兼容的,
例如select name from t where sal>60000
sal字段是decimal类型的,那么优化器很难对这个sql优化,60000是整型,此时我们不能单纯地靠搜索引擎去优化,完全可以靠程序将整型转化为decimal
12、对于表连接要尽可能的把连接条件写全,是有可能提高查询效率的
13、善于使用视图
把表的一个子集进行排序并创建视图,有时可以加速查询,它有助于避免多重排序。
我们可以把要执行多次的sql创建成视图,例如
SELECT cust.name, rcvbles.balance,„„other columns
FROM cust, rcvbles
WHERE cust.customer_id = rcvlbes.customer_id
AND rcvblls.balance>0
AND cust.postcode>“98000”
ORDER BY cust.name
我们创建一个视图
creat view aaa as
SELECT cust.name, rcvbles.balance,„„other columns
FROM cust, rcvbles
WHERE cust.customer_id = rcvlbes.customer_id
AND rcvblls.balance>0
ORDER BY cust.name
然后 select * from aaa where .postcode>“98000” ,这样可以减少io操作(视图中的数据量比主表中的少)从而提高效率
14、能用distinct 就不用groupby,能用unionall 就不要用union (避免distinct操作)
15、注意select into 的使用 会导致锁表
切记 sql 效率主要是考察两个方面 表扫描的次数 索引的利用率
原文:https://www.cnblogs.com/zhhouse/p/10548519.html