我們可以使用數學運算對 MySQL 結果進行排序嗎?\n


是的,我們可以使用 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)

情況 1:這是按降序進行數學運算排序的查詢。

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)

更新於:30-Jul-2019

216 次瀏覽

啟動你的 職業

完成課程,獲得認證

開始
廣告