在MySQL语句或PHP代码中执行简单的算术 [英] Performing simple arithmetic in MySQL statement or in PHP code
问题描述
例如,假设我有一个包含两个整数列start
和end
的数据结构,但是我实际上对起始值和起始值与结束值之间的差异感兴趣.
For instance, say I have a data structure with two integer columns start
and end
, but I'm actually interested in the start and difference between start and end values.
我可以发送此查询:
SELECT start, end - start FROM foo;
或者,我可以做
SELECT start, end FROM foo;
并在PHP中执行$end - $start
操作.将这些简单的操作留给MySQL更好吗?
and perform the $end - $start
operation in PHP. Is it better to leave these sorts of simple operations to MySQL?
推荐答案
我将"$ end-$ start"分类为业务逻辑,并且属于模型层而不是持久层.这意味着要在PHP中执行计算.这有很多好处:
I would classify "$end - $start" as business logic, and that belongs in the model layer not the persistence layer. That means performing the calculation in PHP. This has a number of benefits:
-
如果以后更改数据库,则不需要相同的运算符.
If you change databases later, you don't need the same operators to exist.
您可以控制执行计算的逻辑.
You can source control the logic that performs the calculation.
您可以更彻底地进行单元测试.
You can more thoroughly unit test.
这篇关于在MySQL语句或PHP代码中执行简单的算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!