优化用多个子查询编写的查询

时间:2013-06-13 10:23:56

标签: sql sql-server sql-server-2008

我正在研究如何优化以下使用大量子查询的查询,因为它们往往会降低查询的速度。虽然以下查询工作正常,但它在大约6秒内完成,这是不可接受的。它搜索了大约50万客户的表格。有什么想法吗?

 SELECT (
 (SELECT coalesce(SUM(cashout),0)- 
                        ((select coalesce(sum(Buyin),0) from [Transaction] where TYPE='Credit' and CustomerID=132)
                         + (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Credit' and CustomerID=132))


FROM [transaction]
WHERE TYPE='Credit'
AND CustomerID=132
)
-------------------
+
(
(SELECT coalesce(SUM(cashout),0)
                    - (select coalesce(sum(Paid),0) from [Transaction] where TYPE='Debit' AND Cashout>buyin and CustomerID=132) 
                    +  (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout<buyin and CustomerID=132)
                             from [Transaction] where TYPE='Debit' AND Cashout<Buyin and CustomerID=132)
                    +  (select coalesce(sum(Cashout),0)- (select coalesce(sum(PAID),0) from [Transaction] where TYPE='Debit' AND Cashout=buyin and CustomerID=132)
                             from [Transaction] where TYPE='Debit' AND Cashout=Buyin and CustomerID=132)
FROM [Transaction]
WHERE CustomerID=132
AND TYPE='Debit' 
AND Cashout>buyin )
)
--------------
-
(
select coalesce(sum(Paid),0)
from [Transaction] 
where type='Debit Settlement'
AND CustomerID =132
)
--------------
+
(
select coalesce(sum(Paid),0)
from [Transaction] 
where type='Credit Settlement'
AND CustomerID =132
)
);

2 个答案:

答案 0 :(得分:1)

考虑添加缓存表,其中您预先计算了客户的所有借记,贷记,借记结算和贷记结算。我假设事务表永远不会更新,只插入插入后执行计算的简单触发器。

CREATE TABLE Balance
(
    CustomerID int NOT NULL,
    Debit decimal(18, 2) NOT NULL,
    Credit decimal(18, 2) NOT NULL,
    DebitSettlement decimal(18, 2) NOT NULL,
    CreditSettlement decimal(18, 2) NOT NULL
)

CREATE TRIGGER CalculateBalance
ON [Transaction]
 AFTER INSERT,UPDATE
AS
DECLARE @CustomerID int

SET @CustomerID = (SELECT customerID FROM inserted)

-- Calculate Debit, Credit, DebitSettlement and CreditSettlement for current customer

GO

答案 1 :(得分:0)

尝试为查询执行执行计划,它还提供有关查询滞后的建议,同时尝试在您使用查询的表的字段上创建索引。