Consider I have three tables: order
, sub_order
and product
. The cost of an sub_order
is built upon a complex formula which then depends on the individual costs of the products. The cost of the order
is simply the sum of the sub_order
costs, although this formula might change in the future.
We store the derived field order.order_cost
for convinience.
The questions I have are:
Should business rules be applied to the database layer? If so, is there a way to force the constraint for order_cost
using SQL? That is, order_cost
is always the sum of sub_order_cost
If you want the order cost to always be the sum of the costs from sub_order
, then calculate the value on the fly. There is no need to store the value, unless you have a performance reason. Your question doesn't mention performance as a reason to duplicate the data.
If you want the order cost to be initialized to the sum, then you can use a trigger. That would be strange, though, because I would expect the order to be created before the sub_order
s.
If you want to maintain the order amount as sub_order
s are created, deleted, and updated, then you need triggers. Or, just calculate the values on the fly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.