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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With