减少全表查询扫描
1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。in 和 not in 也要慎用,否则会导致全表扫描
2.减少不必要的通配符全查询,尽量避免模糊查询。
优化存储空间
1.尽可能的使用 varchar 代替 char ,因为首先变长字段存储空间小,可以节省存储空间
2.避免频繁创建和删除临时表,以减少系统表资源的消耗。
3.缓和系统表的资源,应先create table,然后insert插入
4.使用“临时表”暂存中间结果,减少了阻塞,提高了并发性能。
合理使用方法
1.将一个Select语句的结果作为子集,然后从该子集中再进行查询,最好不超过3个。
2.尽量使用多表连接(join)查询(避免子查询)
3.避免在 where 子句中使用 or来链接条件
4.避免在 where 子句中对字段进行函数操作,减少对条件限制和计算。
5.在子查询中,用 exists 代替 in 是一个好的选择。
如:
select name from a where id in(select id from b)
如果我们将这条语句换成下面的写法:
select name from a where exists(select 1 from b where id = a.id)
这样,查询出来的结果一样,但是下面这条语句查询的速度要快的多。
6.不要把SQL语句写得太长,太过冗余
筛选不同年龄段的人数
不同年龄段的人群,定义为三种类型,对三种类型的人进行计数,如下所示,优化准则为尽量减少不必要的全查询。优化如下所示:
select
case when 年龄<=18 then '18岁以下'
when 年龄>18 and 年龄<=28 then '18-28岁'
when 年龄>28 and 年龄<=38 then '28-38岁'
when 年龄>38 and 年龄<=48 then '38-48岁'
when 年龄>48 and 年龄<=58 then '48-58岁'
when 年龄>58 and 年龄<=68 then '58-68岁'
when 年龄>68 then '68岁以上' else '' end field1,
sum(case when chenmo01+chenmo02=0 then 1 else 0 end ) 类型一,
sum(case when chenmo01+chenmo02=1 then 1 else 0 end ) 类型二,
sum(case when chenmo01+chenmo02=2 then 1 else 0 end ) 类型三
from test.table
group by case when 年龄<=18 then '18岁以下'
when 年龄>18 and 年龄<=28 then '18-28岁'
when 年龄>28 and 年龄<=38 then '28-38岁'
when 年龄>38 and 年龄<=48 then '38-48岁'
when 年龄>48 and 年龄<=58 then '48-58岁'
when 年龄>58 and 年龄<=68 then '58-68岁'
when 年龄>68 then '68岁以上' else '' end;