简体   繁体   中英

MySQL: Order by a function of two columns

I have two integer fields A and B in table T .

I want to do something like " SELECT * FROM T ORDER BY f(A,B) DESC "

where f(A,B) is a linear combination of A and B ... ie f(A,B) = mA + nB , where m and n are numbers.

What is the right syntax?

You have two options (at least):

SELECT (n * A + m * B) AS C, *
  FROM T
 ORDER BY C DESC; -- or ORDER BY 1 DESC

Or:

SELECT *
  FROM T
 ORDER BY (n * A + m * B) DESC;

One or the other - possibly both - should work for you in MySQL. The first should work even if the second does not.

Try to keep it simple, use the following:

SELECT * FROM T ORDER BY (m * A + n * B) DESC

where m and n are on your responsibility.

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