Reputation: 563
I need to pull a list of items from a MySQL database and then display them using PHP. I have this figured out. My question is how to change the order of the items. I know you can order them based on a certain field from the database, such as 'id' or similar.
What I need to do is do a calculation on 2 of the fields and then order the resulting list based on that calculation. For example, I need to show an Integer-X from the db and Integer-Y. I also need to show the result of Integer-X minus Integer-Y and I need to sort the list of responses based on that result of Integer-X minus Integer-Y.
Any help would be much appreciated. Thanks in advance.
Upvotes: 3
Views: 193
Reputation: 56779
You can put calculations in the ORDER BY clause:
ORDER BY integerXField - integerYField
Also, if you give an alias to the calculation in the SELECT list, you can sort by the alias:
SELECT
... integerXField - integerYField as theDiff
..
ORDER BY theDiff
Upvotes: 1