MYSQL Order By Sum of Columns
Any idea on how to order the results of a MYSQL query开发者_如何学编程 by the sum of two columns rather than by a single column?
Select * FROM table ORDER BY (col1+col2) desc
I know that won't work., but I hope it conveys what I want to do fairly well.
Thanks!
Why not try before concluding it doesn't work? In point of fact, it does.
Suppose you have a table named 'Students'
Now you want to know the total marks scored by each student. So, type the following query
SELECT Name, S1, S2, SUM(S1+S2) AS TOTAL
FROM Students
GROUP BY Name, S1, S2
ORDER BY Total;
You will get the following result.
I think you should be able to do
SELECT *, col1+col2 as mysum ORDER BY mysum
Which is essentially the same as you already have
I can confirm this is NOT working in some cases.
Check if some value is NULL
Select * FROM table ORDER BY (IFNULL(col1,0)+IFNULL(col2,0)) desc
The query you wrote should work just fine, you can have any expression in the ORDER BY
clause.
精彩评论