2013-06-13 78 views
-1

我正在研究如何優化以下使用大量子查詢的查詢,因爲它們往往會降低查詢的速度。雖然下面的查詢工作正常,但它在大約6秒內完成,這是不可接受的。它搜索一個約500k客戶的表格。有任何想法嗎?優化使用多個子查詢編寫的查詢

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 
) 
); 
+1

你也許可以將所有的這些成一個主查詢和擺脫子查詢與例如'SELECT和'等等(當類型=「信用結算」 AND客戶id = 132 THEN付費END CASE) 。 –

+0

謝謝!這也有幫助。 @MartinSmith –

回答

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 
+0

非常感謝。我不確定爲什麼有些人投下我的問題。有特別的原因嗎? –

+0

不知道爲什麼它得到downvoted。確保在實施觸發器時,您可以使用用於生成結果的查詢來計算餘額,只需將這些值相應地增加到餘額即可。否則插入會很慢。 –

0

試着做了查詢執行計劃這也給有關地方查詢是滯後的建議,也嘗試創建對您正在使用的查詢表的字段索引。