-1

クエリの速度が低下する傾向があるため、多くのサブクエリを使用する次のクエリを最適化する方法を検討しています。次のクエリは問題なく動作しますが、許容できない約 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
)
);
4

2 に答える 2

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
于 2013-06-13T11:01:09.857 に答える
0

クエリの実行計画を実行してみてください。クエリのどこが遅れているかについての提案も得られます。また、クエリを使用しているテーブルのフィールドにインデックスを作成してみてください。

于 2013-06-13T10:31:57.137 に答える