问题
I'm builing a simple e-commerce website, and i'm having some doubts on the order confirmation, and creation...
It's more a question of good practices
then a real question...
Should I: calculate the total order value, and insert on the database, or should i calculate it every time i read/dosomething with the order?
Thanks
回答1:
Best practices in database land means normalised data, and storing values that can be calculated violates that.
You should never store things that you can calculate unless you're absolutely certain that there won't be a discrepancy between the two values.
For example, what do you think should happen if your order consists of two $100 items but the order is set to $150?
Sometimes, there are justifications (usually performance related) to storing values that can be otherwise calculated but the performance gains have to be both significant and necessary, and the possibility of inconsistency either removed or planned for.
You can remove the possibility with things like triggers or materialised views, or you can plan for them by changing business logic to detect and fix problems, or by other means.
But usually, the performance gains aren't worth the extra effort of mitigating the potential problems. After all, how many orders do you see with millions of individual items on them? Other than the US DoD, of course :-)
回答2:
In your transactional database (ie the main, live one) you should not store the calculated value. Summing a dozen rows is nothing.
However, in your analytic database (aka business intelligence db-, data warehouse) you should definitely store the calculated total.
回答3:
As a good practice, you should not store values that can be derived from existing columns in the table.
There are many reasons not to do this such as
If you want to update any of the underlying columns , then you have to update the derived column as well.
size of the table will be increased
etc.. etc..
来源:https://stackoverflow.com/questions/12000269/insert-total-value-of-order-or-calculate-every-time