sqlserver调优

本文介绍SQL Server中使用聚集索引提高查询速度的方法,并对比了不同方式下union操作的效率,展示了如何利用with as语法来简化复杂查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.索引使用
sqlserver聚集索引是真正加快查询速度的东西,而且索引在查询中能否优化是看你建立的索引是否是在你查询的条件或者group by语句中,而不是你的select查询出来的结果字段上。

2.union all/union

select sum(a.AddPnt1) as num,a.ChrId1 FROM(
    select ChrId1,AddPnt1 from W_GldMatchBalanceLog where LogTime BETWEEN '2017-08-14' and '2017-08-15'
UNION ALL
    select ChrId2,AddPnt2 from W_GldMatchBalanceLog where LogTime BETWEEN '2017-08-14' and '2017-08-15'
UNION ALL
    select ChrId3,AddPnt3 from W_GldMatchBalanceLog where LogTime BETWEEN '2017-08-14' and '2017-08-15'
UNION ALL
    select ChrId4,AddPnt4 from W_GldMatchBalanceLog where LogTime BETWEEN '2017-08-14' and '2017-08-15') as a where a.ChrId1 <> 0 GROUP BY ChrId1 ORDER BY num DESC

当你需要取同一个查询结果中的多个值时你可能需要多长查询然后再union而sql2005以后出现了相当于面向对象语言里面的变量的概念的关键字with as能够把查询的结果存起来

select sum(a.AddPnt1) as num,a.ChrId1 FROM(
with cr AS
(SELECT ChrId1,AddPnt1,ChrId2,AddPnt2,ChrId3,AddPnt3,ChrId4,AddPnt4 from W_GldMatchBalanceLog where  LogTime BETWEEN '2017-08-14' and '2017-08-15')
SELECT ChrId1,AddPnt1 FROM cr
UNION ALL
SELECT ChrId2,AddPnt2 FROM cr
UNION ALL
SELECT ChrId3,AddPnt3 FROM cr
UNION ALL
SELECT ChrId4,AddPnt4 FROM cr)

下面代码的效率是上面的一倍多,而且数据量越大差距越明显

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值