在 MySQL IN 子句中獲取返回的記錄集順序?


對於返回的記錄集順序,您需要使用 FIND_IN_SET() 函式。

 例如,讓我們建立一個表。

mysql> create table returnRecordSetOrderDemo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.01 sec)

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

查詢如下。

mysql> insert into returnRecordSetOrderDemo values(100,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into returnRecordSetOrderDemo values(130,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into returnRecordSetOrderDemo values(103,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into returnRecordSetOrderDemo values(134,'Sam');
Query OK, 1 row affected (0.27 sec)
mysql> insert into returnRecordSetOrderDemo values(102,'Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into returnRecordSetOrderDemo values(145,'David');
Query OK, 1 row affected (0.18 sec)

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

查詢如下。

mysql> select *from returnRecordSetOrderDemo;

以下是輸出。

+------+-------+
| Id   | Name  |
+------+-------+
| 100  | John  |
| 130  | Carol |
| 103  | Bob   |
| 134  | Sam   |
| 102  | Larry |
| 145  | David |
+------+-------+
6 rows in set (0.00 sec)

以下是 MySQL 'IN' 子句和返回的記錄集順序的查詢。

mysql> select *from returnRecordSetOrderDemo
-> where Id in(100,145,103,130)
-> order by FIND_IN_SET(Id,'100,145,103,130');

以下是輸出。

+------+-------
| Id   | Name |
+------+-------+
| 100  | John  |
| 145  | David |
| 103  | Bob   |
| 130  | Carol |
+------+-------+
4 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

106 個瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告
© . All rights reserved.