MySQL ORDER BY CASE 在開始處顯示特殊字元


我們首先建立一個表 -

mysql> create table DemoTable
(
   StudentId varchar(40)
);
Query OK, 0 rows affected (0.55 sec)

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

mysql> insert into DemoTable values('10');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('~');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('40');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(NULL);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

此操作將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
| 10        |
| 20        |
| ~         |
| NULL      |
| 40        |
| NULL      |
+-----------+
6 rows in set (0.00 sec)

以下是 MySQL 中特殊字元排序的查詢 -

mysql> select *from DemoTable
   order by case when StudentId not like '%[^a-zA-Z0-9]%' THEN 80
   when StudentId is null then 98
   else 85 end,StudentId;

此操作將產生以下輸出 -

+-----------+
| StudentId |
+-----------+
| ~         |
| 10        |
| 20        |
| 40        |
| NULL      |
| NULL      |
+-----------+
6 rows in set (0.03 sec)

更新時間:04-Oct-2019

516 次檢視

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.