使用 MySQL 實現特定的記錄排序


要設定特定的記錄順序,請使用 ORDER BY LIKE。讓我們首先建立一個表 -

mysql> create table DemoTable808(Value varchar(100));
Query OK, 0 rows affected (0.61 sec)

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

mysql> insert into DemoTable808 values('smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable808 values('Adamsmith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable808 values('Carolsmith');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable808 values('smithJohn');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from DemoTable808;

這將產生以下輸出 -

+------------+
| Value      |
+------------+
| smith      |
| Adamsmith  |
| Carolsmith |
| smithJohn  |
+------------+
4 rows in set (0.00 sec)

以下是設定特定順序的查詢 -

mysql> select *from DemoTable808
order by case when Value like 'smith%' then 0 else 1 end asc,Value asc;

這將產生以下輸出 -

+------------+
| Value      |
+------------+
| smith      |
| smithJohn  |
| Adamsmith  |
| Carolsmith |
+------------+
4 rows in set (0.00 sec)

更新於:2019-09-03

70 次瀏覽

開始你的 事業

完成教程,獲得證書

開始
廣告
© . All rights reserved.