【发布时间】:2010-04-07 18:10:31
【问题描述】:
我有一个包含产品销售历史的数据库。例如下表
CREATE TABLE SalesHistoryTable (
OrderID, // Order Number Unique to all orders
ProductID, // Product ID can be used as a Key to look up product info in another table
Price, // Price of the product per unit at the time of the order
Quantity, // quantity of the product for the order
Total, // total cost of the order for the product. (Price * Quantity)
Date, // Date of the order
StoreID, // The store that created the Order
PRIMARY KEY(OrderID));
该表最终将有数百万个事务。由此,可以为不同地理区域的产品创建配置文件(基于 StoreID)。作为数据库查询,创建这些配置文件可能非常耗时。例如。
SELECT ProductID, StoreID,
SUM(Total) AS Total,
SUM(Quantity) QTY,
SUM(Total)/SUM(Quantity) AS AvgPrice
FROM SalesHistoryTable
GROUP BY ProductID, StoreID;
上述查询可用于根据任何特定商店的产品获取信息。然后,您可以确定哪家商店卖得最多,赚的钱最多,平均卖得最多/最少。这将是非常昂贵的使用作为一个正常的查询运行随时。假设存储大小不是问题,有哪些设计决策可以让这些类型的查询运行得更快。例如,我可以创建另一个包含重复信息的表。 商店 ID(键)、产品 ID、TotalCost、QTY、AvgPrice 并提供一个触发器,以便在收到新订单时,在新表中更新该商店的条目。更新的成本几乎为零。
在上述情况下应该考虑什么?
【问题讨论】:
-
您自己的答案是针对此类查询的。在数据库中缓存结果将比您可以做的任何其他事情提供更大的加速。这种方法的另一个好处是,如果事情由于某种原因不同步,您可以在紧要关头扔掉所有东西并使用一个查询重新创建表。