使用 MySQL IN() 按特定順序顯示 ID?


要按特定順序(即你選擇順序)顯示 ID,請使用 FIELD() 方法。

讓我們首先建立一個表 -

mysql> create table DemoTable
   (
   UserId int
   );
Query OK, 0 rows affected (0.64 sec)

以下是對使用 insert 命令在表中插入一些記錄的查詢 -

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.13 sec)

以下是使用 select 命令從表中顯示記錄的查詢 -

mysql> select *from DemoTable;

這將產生以下輸出

+--------+
| UserId |
+--------+
| 100    |
| 10     |
| 40     |
| 80     |
| 70     |
| 60     |
+--------+
6 rows in set (0.00 sec)

以下是使用 IN() 和 FIELD() 按照你選擇順序顯示記錄的查詢 -

mysql> select UserId from DemoTable where UserId IN(60,100,10,80,40,70)
order by field(UserId,60,100,10,80,40,70);

這將產生以下輸出 -

+--------+
| UserId |
+--------+
| 60     |
| 100    |
| 10     |
| 80     |
| 40     |
| 70     |
+--------+
6 rows in set (0.03 sec)

更新於: 30-7-2019

194 檢視

開啟你的職業生涯

完成課程並獲得認證

入門
廣告
© . All rights reserved.