Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL sort on a calculation

Tags:

sorting

mysql

Is it possible to sort on a calculation of 2 rows in mySQL? For example, I have 2 rows, lp and ap I'm trying to do something like this:

SELECT * from myTbl WHERE 1 ORDER BY (lp/ap)

Which isn't throwing an error, but its also not sorting by the results of that calculation. Is there a way to do this, or do I have to store lp/ap in the database?

like image 629
Stomped Avatar asked Mar 03 '10 08:03

Stomped


People also ask

How do I sort a value in MySQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can you do calculations in MySQL?

5 Date Calculations. MySQL provides several functions that you can use to perform calculations on dates, for example, to calculate ages or extract parts of dates.

Can we sort by two columns in MySQL?

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.

Which clause is used to sort data in MySQL?

The ORDER BY clause is used to sort the result-set in ascending or descending order.


1 Answers

Yes, it is possible, and it does work. Check out the following test:

CREATE TABLE a(a INT, b INT);

INSERT INTO a VALUES (1, 1);
INSERT INTO a VALUES (1, 2);
INSERT INTO a VALUES (1, 3);
INSERT INTO a VALUES (1, 4);
INSERT INTO a VALUES (1, 5);
INSERT INTO a VALUES (1, 6);
INSERT INTO a VALUES (2, 1);
INSERT INTO a VALUES (2, 2);
INSERT INTO a VALUES (2, 3);
INSERT INTO a VALUES (2, 4);
INSERT INTO a VALUES (2, 5);
INSERT INTO a VALUES (2, 6);

SELECT a.a, a.b, (a/b) FROM a ORDER BY (a/b);

+------+------+--------+
| a    | b    | (a/b)  |
+------+------+--------+
|    1 |    6 | 0.1667 | 
|    1 |    5 | 0.2000 | 
|    1 |    4 | 0.2500 | 
|    2 |    6 | 0.3333 | 
|    1 |    3 | 0.3333 | 
|    2 |    5 | 0.4000 | 
|    1 |    2 | 0.5000 | 
|    2 |    4 | 0.5000 | 
|    2 |    3 | 0.6667 | 
|    2 |    2 | 1.0000 | 
|    1 |    1 | 1.0000 | 
|    2 |    1 | 2.0000 | 
+------+------+--------+

SELECT a.a, a.b FROM a ORDER BY (a/b); would return the same results.

like image 89
Daniel Vassallo Avatar answered Oct 19 '22 04:10

Daniel Vassallo