开发者

Performing simple arithmetic in MySQL statement or in PHP code

开发者 https://www.devze.com 2023-03-28 02:01 出处:网络
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.

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.

I could send this query:

SELECT start, end - start FROM foo;

or, I could just do

SELECT start, end FROM foo;

and perform the $end - $start operation in PHP. Is it better to leave these sorts of simple operations to MySQL?


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.


I'm one of those database should do data things so unless you're using an aggregate function most things like this should be done on the application end. Now for simplicity here your query could be just

SELECT start, (end - start) AS difference FROM foo;

but for more complicated things it's recommended that you do a lot of the data manipulation in the application side.

The other answer says to put the logic as close to the DB as possible (which IMO is a horrid idea) although in this case I see nothing wrong with what you're doing but just remember that the database is already doing a lot of work to just get you the data, if you're going to be doing a lot of logic on the database it's going to make it just that much slower. For small applications it's not a big deal but for large scale applications you will see implications very quickly not only in performance but adding new functionality (splitting logic between database and application level gets very confusing and hard to refactor).


Normally any view transformation should be handled in presentation layer. In your case your model is designed with start & end fields, so you should expose this fields from sql.


MySQL can perform some basic arithmetic. However, it is definitely better to perform that sort of arithmetic in PHP if you're already using the data in PHP anyway.

MySQL is meant more for simply storing and extracting relational data.


For simple operations I would use MYSQL. I'm not a guru, but I like to keep things as simple and clean as posible so where it is possible I use MYSQL built-in functions to do the stuff that can be done with php. In other words - using MYSQL would lower the amount of code and formatting necessary to display the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消