一次Sql语句的优化实战之旅

1.使用union all 代替 in

数据量很大,优化前差不多2分钟,优化后1s.

低效sql:
select col1,col2,col3 from table where id in(1,2,3,4,5);
高效sql:
select col1,col2,col3 from table where id=1
union all
select col1,col2,col3 from table where id=2
union all
select col1,col2,col3 from table where id=3
union all
select col1,col2,col3 from table where id=4
union all
select col1,col2,col3 from table where id=5

2.使用 count(1) over() 代替 count(1)或者count(*)

当时用分页需要计算总的记录数时,count(1) over()的效率远远高于 count(1)

低效sql:
select count(1) from table t1 left outer join table2 t2
on t1.col1=t2.col2 
或者
SELECT col1,col2 FROM (SELECT col1,col2, ROW_NUMBER() OVER(col) AS [num] FROM table where 1=1  ) AS TEMP1 where [num] >= startIndex and [num] <= endIndex ; SELECT COUNT(1) as [totalCount] FROM table where 1=1;

高效sql:
select totalCount=count(1) over() from table t1 left outer join table2 t2 on t1.col1=t2.col2 
或者
SELECT col1,col2,TotalCount FROM (SELECT col1,col2, ROW_NUMBER() OVER(col) AS [num],COUNT(*) over() TotalCount FROM table where 1=1 ) AS TEMP1 where [num] >= startIndex and [num] <= endIndex 

3.使用 row_number() over(partition by col1,col2 order by col) 代替 max(col) group by col1 col2

低效的sql:
select col1,col2 from table where col in(select max(col) from table group by col1,col2 order by col desc)
高效的sql:
select col1,col2 from (select num=row_number() over(partition by col1,col2 order by col desc)  from table ) where num=1 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值