一尘不染

MySQL排序计算

mysql

在MySQL中是否可以对2行的计算进行排序?例如,我有2行,lp并且ap我正在尝试执行以下操作:

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

这不会引发错误,但是也不会根据该计算结果进行排序。有没有办法做到这一点,还是我必须将lp / ap存储在数据库中?


阅读 260

收藏
2020-05-17

共1个答案

一尘不染

是的,这是可行的,而且确实可行。查看以下测试:

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); 将返回相同的结果。

2020-05-17