sql的基础优化,持续更新中...

1、对查询进行优化,应避免全表扫描,首先应考虑在where和order by涉及的列上建立索引

2、尽量避免在where字句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:select id form s where num is null 。可以在num上设置默认值0,确保表中列num没有null,然后这样查询:select id form s where num=0

3、应尽量避免在where 字句中使用or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:select id from s where num=2 or num=3。可以这样查询:select id from s where num =2 union all select id from s where num=3

4、in 和not in 也要慎用。否则会导致全表扫描,如:select id from where num in (1,2,3)。对于这样连续的数值,可以使用区间查询select id from s where num between 1 and 3

5、应尽量避免在where 字句中进行表达式操作:这将导致引擎放弃使用索引而进行全表扫描,如:select id from s where num/2=100应改为:select id from s where num=100*2

6、应尽量避在where 字句中进行函数操作,这将导致引擎放弃使用索引进行全表扫描,如:select id from s where substring(name,1,3)='abc'-----name以abc开头的id。应改为:select id from s where name like 'abc%'

 

原文:https://blog.csdn.net/jie_liang/article/details/77340905

posted @ 2021-04-20 10:32  零点001  阅读(42)  评论(0)    收藏  举报