今天读到一篇关于老鸟的SQL的经验之谈,参考后写下这篇建议
-
避免在select f1,(select f2 from tableB ).... from tableA 这样得到字段列。 直接用tableA和tableB关联得到A.f1,B.f2就可以了。
-
避免隐含的类型转换,如:
select id from table where emp_id='8' (错) select id from table where emp_id=8 (对)
emp_id是整数型,用'8'会默认启动类型转换,增加查询的开销。
-
使用关键字代替函数,如:
select id from table where UPPER(dept) like 'TECH_DB' (错) select id from table where SUBSTR(dept,1,4)='TECH' (错) select id from tablewhere dept like 'TECH%' (对)
-
不要在字段上用转换函数,尽量在常量上用,如:
select id from table where to_char(time,'yyyy-mm-dd')='2012-10-31' (错) select id from table where time=to_date('2012-10-31','yyyy-mm-dd') (对)
-
.不使用联接做查询,如:
select id from table where first_name || last_name like 'Jo%' (错) select id from table where first_name like 'Jo%' OR last_name like 'Jo%'(对)
-
尽量避免前后都用通配符,如:
select id from table where name like '%Jo%' (错) select id from table where name like 'Jo%' (对)
-
判断条件顺序,如:
select id from employee where creat_date-30>to_date('2012-10-31','yyyy-mm-dd') (错) select id from employee where creat_date >to_date('2012-10-31','yyyy-mm-dd')+30 (对)
-
尽量使用exists而非in,当然这个也要根据记录的情况来定用exists还是用in, 通常的情况是用exists
select id from table where age in (select age from table2 where....) (错) select id from table where age exists (select 'X' from table2 where ....) (对)
-
使用not exists 而非not in,代码和上面的类似。
-
减少查询表的记录数范围
- 正确使用索引
索引可以提高速度,一般来说,选择度越高,索引的效率越高。
-
索引类型
唯一索引,对于查询用到的字段,尽可能使用唯一索引。
还有一些其他类型,如位图索引,在性别字段,只有男女的字段上用
-
在经常进行连接,但是没有指定为外键的列上建立索引
- 在频繁进行排序会分组的列上建立索引,如经常做group by 或 order by 操作的字段。
- 在条件表达式中经常用到的不同值较多的列上建立检索,在不同值少的列上不建立索引。 如性别列上只有男,女两个不同的值,就没必要建立索引(或建立位图索引)。 如果建立索引不但不会提高查询效率,反而会严重降低更新速度。
- 在值比较少的字段做order by时,翻页会出现记录紊乱问题,要带上id字段一起做order by.
- 不要使用空字符串进行查询,如:
select id from table where name like '%%' (错)
- 尽量对经常用作group by的关键字段做索引。
- 正确使用表关联,利用外连接替换效率十分低下的not in运算,大大提高运行速度。如:
select a.id from table a where a.num not in (select num from table1 where job ='SALE') (错)
-
使用临时表,在必要的情况下,为减少读取次数,可以使用经过索引的临时表加快速度。
-
减少使用Order by/Group by字段
-
尽量规避大事务的SQL,大事务的SQL会影响数据库的并发性能及主从同步
-
分页语句limit问题
-
删除表所有记录使用truncate,不用delete
-
不让mysql干多余的事,例如计算