algorithmicCoder
algorithmicCoder

Reputation: 6799

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 ... i.e f(A,B) = mA + nB, where m and n are numbers.

What is the right syntax?

Upvotes: 7

Views: 4549

Answers (2)

Oleg Dok
Oleg Dok

Reputation: 21776

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.

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 754710

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.

Upvotes: 13

Related Questions