對資料列進行排序以在 MySQL 中檢索最大文字值


為此,您可以將 ORDER BY 與一些聚合函式 right() 一起使用。我們首先建立一個數據表 -

mysql> create table DemoTable1487
   -> (
   -> StudentCode text
   -> );
Query OK, 0 rows affected (0.91 sec)

使用 insert 命令插入一些記錄到資料表中 -

mysql> insert into DemoTable1487 values('560');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable1487 values('789');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1487 values('STUDENT78');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1487 values('John89');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1487 values('Carol101');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1487 values('STUDENT98');
Query OK, 1 row affected (0.13 sec)

使用 select 語句顯示資料表中的所有記錄 -

mysql> select * from DemoTable1487;

這將產生以下輸出 -

+-------------+
| StudentCode |
+-------------+
| 560         |
| 789         |
| STUDENT78   |
| John89      |
| Carol101    |
| STUDENT98   |
+-------------+
6 rows in set (0.00 sec)

這是對資料列進行排序以檢索最大文字值所需的查詢 -

mysql> select * from DemoTable1487 where StudentCode LIKE 'STUDENT%'
   -> order by cast(right(StudentCode,length(StudentCode)-length('STUDENT')) as UNSIGNED) desc
   -> limit 1;

這將產生以下輸出 -

+-------------+
| StudentCode |
+-------------+
| STUDENT98   |
+-------------+
1 row in set (0.04 sec)

更新時間:2019-12-11

84 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.