mysql对计算进行排序

wpx232ag  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(197)

在mysql中是否可以按2行计算排序?例如,我有两行, lp 以及 ap 我试着这样做:

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

它不会抛出错误,但也不会根据计算结果进行排序。有没有办法做到这一点,或者我必须在数据库中存储lp/ap?

qpgpyjmq

qpgpyjmq1#

是的,这是可能的,而且确实有效。检查以下测试:

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

1tu0hz3e2#

SELECT *, (lp/ap) AS calculation from myTbl ORDER BY calculation

只要(lp/ap)是有效的,就应该这样做。

nwwlzxa7

nwwlzxa73#

你可能有更多的机会

SELECT *, (lp/ap) as n from myTbl ORDER BY n

相关问题