如何在 MySQL 中對包含數字的字串進行排序?


在某些情況下使用 ORDER BY。我們建立一個表 -

mysql> create table demo18
−> (
−> value text
−> );
Query OK, 0 rows affected (1.18 sec)

藉助插入命令向表中插入一些記錄 -

mysql> insert into demo18 values('John Smith');
Query OK, 1 row affected (0.06 sec)

mysql> insert into demo18 values('2J John has 58');
Query OK, 1 row affected (0.17 sec)

mysql> insert into demo18 values('2J John has 9');
Query OK, 1 row affected (0.09 sec)

使用 select 語句在表中顯示記錄 -

mysql> select *from demo18;

這將生成以下輸出 -

+----------------+
| value          |
+----------------+
| John Smith     |
| 2J John has 58 |
| 2J John has 9  |
+----------------+
3 rows in set (0.00 sec)

以下是對排序的查詢 -

mysql> select *from demo18
−> order by regexp_replace(value, '[0&minus9]*$', ''),
−> length(value),
−> value;

這將生成以下輸出 -

+----------------+
| value          |
+----------------+
| 2J John has 9  |
| 2J John has 58 |
| John Smith     |
+----------------+
3 rows in set (0.14 sec)

更新日期: 19-11-2020

653 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.