Insert Total value of order, or calculate every time?

故事扮演 提交于 2019-12-10 22:37:43

问题


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

  1. If you want to update any of the underlying columns , then you have to update the derived column as well.

  2. size of the table will be increased

etc.. etc..



来源:https://stackoverflow.com/questions/12000269/insert-total-value-of-order-or-calculate-every-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!