【问题标题】:Optimise aggregation query优化聚合查询
【发布时间】:2010-12-18 06:22:42
【问题描述】:

我正在寻找一种方法来优化以下内容:

SELECT 
    (SELECT SUM(amount) FROM Txn_Log WHERE gid=@gid AND txnType IN (3, 20)) AS pendingAmount,
    (SELECT COUNT(1) FROM Txn_Log WHERE gid = @gid AND txnType = 11) AS pendingReturn,
    (SELECT COUNT(1) FROM Txn_Log WHERE gid = @gid AND txnType = 5) AS pendingBlock

其中@gid 是一个参数,gid 是该表上的一个索引字段。问题:每个子查询在同一组条目上重新运行 - 三个重新运行两个太多了。

【问题讨论】:

    标签: sql optimization aggregation


    【解决方案1】:

    你可以这样做:

    select
       sum(case when txnType in (3,20) then amount else 0 end) as pendingAmount,
       sum(case txnType when 11 then 1 else 0 end) as pendingReturn,
       sum(case txnType when 5 then 1 else 0 end) as pendingBlock
    from
       Txn_Log
    where
       gid = @gid
    

    【讨论】:

    • 很好,也可以用txnType IN (3, 20, 11, 5)限制初始选择
    • 另外,使用 [gid] 和 [txnType] 字段的索引,甚至可能使用 [amount] 来避免查询甚至查看表本身。 [gid]、[txnType]、[amount] 上的覆盖索引带来的最大好处
    【解决方案2】:

    你不能这样做吗

    SELECT sum(amount),count(1), txnType
    FROM Txn_log
    WHERE gid = @gid AND
        txnType in (3,5,11,20)
    group by txnType
    

    然后以编程方式处理其余部分?

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2010-10-23
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      相关资源
      最近更新 更多