僅按照 MySQL 的升序排列顯示記錄的列表


要按特定順序顯示記錄列表,您需要設定條件並使用 ORDER BY。為此,請使用 ORDER BY CASE 語句。首先,讓我們建立一個表 -

mysql> create table DemoTable2039
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.62 sec)

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

mysql> insert into DemoTable2039 values('John Doe');
Query OK, 1 row affected (0.15 sec)

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

mysql> insert into DemoTable2039 values('Chris Brown');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable2039 values('Adam Smith');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable2039 values('David Miller');
Query OK, 1 row affected (0.09 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable2039;

這將產生以下輸出 -

+--------------+
| Name         |
+--------------+
| John Doe     |
| John Smith   |
| Chris Brown  |
| Adam Smith   |
| David Miller |
+--------------+
5 rows in set (0.00 sec)

以下是按升序顯示特定記錄列表的查詢 -

mysql> select *from DemoTable2039
   -> order by
   -> case when Name like '%Smith%' then 101
   -> else
   -> 100
   -> end,
   -> Name;

這將產生以下輸出 -

+--------------+
| Name         |
+--------------+
| Chris Brown  |
| David Miller |
| John Doe     |
| Adam Smith   |
| John Smith   |
+--------------+
5 rows in set (0.37 sec)

更新日期: 07-Apr-2020

121 次瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

立即開始
廣告