我经常看到订单或发票的 line_item 表从其他表中复制一个或多个字段,以便在客户下达产品订单时对其进行快照。
然而,在我的模式中,我可以在不复制数据的情况下生成订单视图。所以查找订单/产品/价格数据会稍微贵一点,但我可以节省复制/插入的时间、空间和冗余。我知道复制/插入是一次性事务,而查找将需要多次 - 但是,我只处理给定表中的数千条记录,我不希望性能是一个问题。
因此,因为 a) 我的模式支持无需快照的准确查找,并且 b) 我对查找优化没有强烈需求,所以我认为运行计算而不是快照是有意义的-射击。或者有什么我遗漏的东西,在这种情况下我应该总是拍一张快照吗?
以下是查找计算的示例:
# display order items for a particular order on a particular date
# get order, products and base prices from order_id
order_products = SELECT * FROM order_has_product ohp
INNER JOIN price ON (price.product_id = ohp.product_id)
INNER JOIN order ON (order.id = ohp.order_id)
WHERE order_id = ?
# calculate price of each product at order.datetime_opened
for op in order_products:
tax = SELECT SUM(tax.rate) FROM product_has_tax pht
INNER JOIN tax ON (tax.id = pht.tax_id)
WHERE pht.product_id = op.product_id
AND tax.date_start <= op.datetime_opened
AND tax.date_end >= op.datetime_opened
discount_product = SELECT SUM(discount.rate) FROM product_has_discount phd
INNER JOIN discount ON (discount.id = phd.discount_id)
WHERE phd.product_id = op.product_id
AND discount.date_start <= op.datetime_opened
AND discount.date_end >= op.datetime_opened
discount_customer = SELECT SUM(discount.rate) FROM customer_has_discount chd
INNER JOIN discount ON (discount.id = chd.discount_id)
WHERE chd.customer_id = op.customer_id
AND discount.date_start <= op.datetime_opened
AND discount.date_end >= op.datetime_opened
AND (chd.date_used_limited IS NULL OR chd.date_used_limited = op.datetime_opened)
discount = discount_product + discount_customer
price = op.price * (1-discount) * (1+tax)