Simple calculations, especially for aggregation type scenarios, should definitely be handled on the database for multiple reasons:
Less data returned over the wire from the database
Database can take advantage of indexing
Database is faster at aggregating data, because that's what they're made for.
Using code such as PHP makes sense only when you have really complex calculations or business logic that are not handled easily by a database tool, or when using logic that databases do not do efficiently, such as string manipulation.
The general rule of thumb is something like this:
Return as little data as absolutely necessary from the database, and apply any logic that reduces the number of rows at the database side.
Work with the data returned to do complex business logic and markup (i.e., HTML) with your coding language.
发布评论
评论(2)
出于多种原因,绝对应该在数据库上处理简单的计算,尤其是聚合类型的场景:
仅当您有数据库工具无法轻松处理的非常复杂的计算或业务逻辑,或者使用数据库不能有效执行的逻辑(例如字符串操作)时,使用诸如 PHP 之类的代码才有意义。
一般的经验法则是这样的:
Simple calculations, especially for aggregation type scenarios, should definitely be handled on the database for multiple reasons:
Using code such as
PHP
makes sense only when you have really complex calculations or business logic that are not handled easily by a database tool, or when using logic that databases do not do efficiently, such as string manipulation.The general rule of thumb is something like this:
为什么要重写代码?
SUM(somefield) WHERE (condition)
可以准确地满足您的需求。相反,你建议这样做:
我不明白为什么。 ;-)
这对于代码来说是纯粹的,事实上,在第二种情况下会传输更多的数据,仅举一例。
Why would you rewrite code?
SUM(somefield) WHERE (condition)
gives you exaclty what you need.On the contrary, you suggest to do something like this:
I don't see why. ;-)
And that's pure for the code, indeed more data is being transported in the second case, to name one thing.