1、对查询进行优化,应尽量避免全表扫描,先应考虑在 where 及 order by 涉及的列上建立索引。
2、应尽量避免在 where 句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num is null
可以在 num 上设置默认值 0 或者 -1,确保表中 num 列没有 null 值,然后这样查询: select id from t where num = 0
3、应尽量避免在 where 语句中使用 != 或 <> 操作符,否则会导致查询引擎放弃使用索引而进行全表扫描。
4、应尽量避免在 where 语句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num = 10 or nun = 20
可以这样查询:
select id from t where num = 10 union all
select id from t where num = 20
5、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
6、全模糊查询和左半模糊查询也将导致全表扫描
如: select id from t where name like ‘%abc%’ 和 select id from t where name like ‘%abc’
要使用模糊查询尽量使用右模糊查询:
select id from t where name like ‘abc%’
7、应尽量避免在 where 语句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描,如: select id from t where num/2 = 10
应改为:
select id from t where num = 10 * 2
8、应尽量避免在 where 语句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描,如: select id from t where substring(name, 1, 3) = ‘abc’
应改为(右模糊查询):
select id from t where name like ‘abc%’
9、不要在 where 语句中的 “=” 左边进行函数操作、算数运算或者其它表达式运算,否则系统将可能无法正确使用索引。
10、在使用索引字段作为条件时,如果该索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引, 否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致。
11、用 exists 代替 in 是一个好选择:
select num from a where num in (select num form b) 可用下面的语句替换:
select num from a where exists (select 1 from b where num = a.num)
12、并不是所有索引对查询都有效,SQL是根据表中数据来进行查询优化的,当索引列有数据重复时,SQL查询可能不会取索引,如表中有字段 sex,值 male 和 female 几乎各占一半,那么即使在 sex 上建了索引也对查询效率起不了作⽤。
13、索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 和 update 的效率,因为 insert 或 update 时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。
14、尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,⽽对于数值型⽽⾔只需要⽐较⼀次就可以了。
15、尽可能的使用 varchar 代替 char ,因为⾸先变长字段存储空间⼩,可以节省存储空间,其次对于查询来说,在⼀个较⼩的字段内搜索效率显然要⾼些。
16、任何地方都不要使用 select * from t,具体的字段列表代替 “ * ”,不要返回用不到的任何字段。