Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
algorithmicCoder Avatar asked Jan 08 '12 06:01

algorithmicCoder


People also ask

Can I ORDER BY 2 columns mysql?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.

Can we use ORDER BY for 2 columns?

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

How does ORDER BY work with multiple columns?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.

Can we use ORDER BY 2 desc in SQL?

If you prefer, you can use the positions of the column in the ORDER BY clause. See the following statement: SELECT name, credit_limit FROM customers ORDER BY 2 DESC, 1; In this example, the position of name column is 1 and credit_limit column is 2.


1 Answers

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.

like image 178
Jonathan Leffler Avatar answered Oct 30 '22 20:10

Jonathan Leffler