技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

我们可以使用数学运算对 MySQL 结果进行排序吗?\

mysqlmysqli database

是的,我们可以使用 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 rows 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 rows 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 rows in set (0.00 sec)


相关文章