用於按數值差異顯示記錄的 MySQL 查詢?


使用 ORDER BY 並設定差值以顯示按數值差排序的記錄。以下是語法 −

select *from yourTableName
order by (yourIntegerColumnName1 - yourIntegerColumnName2);

我們首先建立一個表 −

mysql> create table DemoTable1313
-> (
-> Name varchar(20),
-> Score1 int,
-> Score2 int
-> );
Query OK, 0 rows affected (3.48 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable1313 values('Chris',40,60);
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1313 values('David',70,50);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1313 values('Adam',35,30);
Query OK, 1 row affected (0.18 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable1313;

輸出

+-------+--------+--------+
| Name  | Score1 | Score2 |
+-------+--------+--------+
| Chris |     40 |     60 |
| David |     70 |     50 |
| Adam  |     35 |     30 |
+-------+--------+--------+
3 rows in set (0.00 sec)

以下是對按數值差排序的查詢 −

mysql> select *from DemoTable1313
-> order by (Score1-Score2);

輸出

+-------+--------+--------+
| Name | Score1  | Score2 |
+-------+--------+--------+
| Chris | 40     |    60  |
| Adam  | 35     |    30  |
| David | 70     |    50  |
+-------+--------+--------+
3 rows in set (0.00 sec)

更新於:2019 年 11 月 4 日

53 次瀏覽

啟動你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.