SQL语句的性能优化

81 篇文章 2 订阅
27 篇文章 0 订阅
减少全表查询扫描

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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值