是否可以使用数学操作对MySQL结果进行排序?
是的,我们可以使用ORDER BY子句进行数学运算排序。让我们先创建一个表:
mysql> create table orderByMathCalculation
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Quantity int,
-> Price int
-> );
Query OK, 0 rows affected (0.57 sec)
以下是使用insert命令将一些记录插入表中的查询:
mysql> insert into orderByMathCalculation(Quantity,Price) values(10,50);
Query OK, 1 row affected (0.21 sec)
mysql> insert into orderByMathCalculation(Quantity,Price) values(20,40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into orderByMathCalculation(Quantity,Price) values(2,20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into orderByMathCalculation(Quantity,Price) values(11,10);
Query OK, 1 row affected (0.24 sec)
以下是使用select语句从表中显示所有记录的查询:
mysql> select *from orderByMathCalculation;
这将产生以下输出:
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 1 | 10 | 50 |
| 2 | 20 | 40 |
| 3 | 2 | 20 |
| 4 | 11 | 10 |
+----+----------+-------+
4 row in set (0.00 sec)
情况1: 以下是按升序数学运算排序的查询。
mysql> select *from orderByMathCalculation order by Quantity*Price;
这将产生以下输出:
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 3 | 2 | 20 |
| 4 | 11 | 10 |
| 1 | 10 | 50 |
| 2 | 20 | 40 |
+----+----------+-------+
4 row in set (0.00 sec)
情况2: 以下是按降序数学运算排序的查询。
mysql> select *from orderByMathCalculation order by Quantity*Price desc;
这将产生以下输出:
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 2 | 20 | 40 |
| 1 | 10 | 50 |
| 4 | 11 | 10 |
| 3 | 2 | 20 |
+----+----------+-------+
4 row in set (0.00 sec)
阅读更多:MySQL 教程
极客教程