根據特定欄位值對 MySQL 中的進行排序


若要在 MySQL 中按特定欄位值首先進行排序,請使用 ORDER BY FIELD()。我們首先建立一個數據表 −

mysql> create table DemoTable849(Color varchar(100));
Query OK, 0 rows affected (0.56 sec)

使用 insert 命令向表中插入一些記錄 −

mysql> insert into DemoTable849 values('RED');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable849 values('ORANGE');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable849 values('BLUE');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable849 values('GREEN');
Query OK, 1 row affected (0.12 sec)

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

mysql> select *from DemoTable849;

將會產生以下輸出 −

+--------+
| Color  |
+--------+
| RED    |
| ORANGE |
| BLUE   |
| GREEN  |
+--------+
4 rows in set (0.00 sec)

以下是按特定值首先進行排序的查詢 −

mysql> select *from DemoTable849 order by field(Color,'RED','GREEN','BLUE','ORANGE');

將會產生以下輸出 −

+--------+
| Color  |
+--------+
| RED    |
| GREEN  |
| BLUE   |
| ORANGE |
+--------+
4 rows in set (0.00 sec)

更新於: 03-Sep-2019

321 人次訪問

開啟你的 職業

完成課程取得認證

開始
廣告