XLordalX XLordalX - 2 months ago 10
MySQL Question

MYSQL - Order by multiple integer fields added together

I have 2 column (

column1
and
column2
) and I want to select all rows ordered by these 2 columns combined (added together, column1 + column2). Both columns are int values.

How would I do something like this:

SELECT column1, column2 FROM table ORDER BY column1 + column2 DESC;


Example:

----------------------------
| ID | Column 1 | Column 2 |
----------------------------
| 1 | 70 | 20 |
----------------------------
| 2 | 10 | 40 |
----------------------------
| 3 | 30 | 50 |
----------------------------


Ordered output:


  1. Row #1

  2. Row #3

  3. Row #2


Answer

You've already got it right. Here is a sqlfiddle that shows it in action.

I've added a second way of querying the table to make it more obvious that the results are returned in the correct order. For this simple example it isn't needed but it's a good way to "debug" your queries, add calculated values to the select portion and initially skip the order by to eliminate errors.

select id, one, two, one + two as sum from ints order by one + two desc;

select id, one, two, one + two as sum from ints order by sum desc; 
Comments