正如在評論中指出的,我通常不喜歡存儲冗餘,可能不正確的數據。但是,如果在運行中計算總計時存在性能問題,則下一個最佳選擇是讓系統爲您執行計算。如果您使用索引視圖,則這是一個選項。
表設置:
create table dbo.Orders (
OrderID int not null,
/* NO Total here */
constraint PK_Orders PRIMARY KEY (OrderID)
)
go
create table dbo.Items (
ItemID int not null,
Cost decimal (19,4) not null,
constraint PK_Items PRIMARY KEY (ItemID)
)
go
create table dbo.OrderItems (
OrderItemID int not null,
OrderID int not null,
ItemID int not null,
/* I'd normally prefer Order/Item/Quantity and making Order/Item the PK */
constraint PK_OrderItems PRIMARY KEY (OrderItemID),
constraint FK_OrderItems_Orders FOREIGN KEY (OrderID) references Orders (OrderID),
constraint FK_OrderItems_Items FOREIGN KEY (ItemID) references Items (ItemID)
)
現在我們可以創建視圖:
create view dbo.OrderTotals
with schemabinding
as
select
OrderID,
COUNT_BIG(*) as LineCount, /* Required for indexed view with aggregate */
SUM(Cost) as OrderTotal
from
dbo.Items i
inner join
dbo.OrderItems o
on
i.ItemID = o.ItemID
group by
OrderID
go
create unique clustered index IX_OrderTotals on OrderTotals (OrderID)
現在,當你執行插入,更新和刪除針對的OrderItems或項目表,這種觀點的指數(其中實際包含所有視圖數據)會自動爲您更新。
這樣可以避免您在使用時可能會漏掉的拐角案件的任何擔憂。觸發器手動執行更新。
我建議不要*存儲*數據,你可以*計算*,除非和直到你可以證明一個實際的性能問題,只是在飛行中計算結果。只要你*存儲*冗餘數據,你打開自己的機會,它*錯*。 –