简体   繁体   中英

Change order of items coming from MySQL in PHP

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM