MySQL 查询使用 `user_id` IN (1,2,3) AND `name` 根据自定义顺序进行排序


要实现 IN() 来进行自定义排序,请使用 ORDER BY CASE。

让我们首先创建一个表 -

mysql> create table DemoTable752 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100)
);
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable752(Name) values('John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable752(Name) values('Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable752(Name) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable752(Name) values('Mike');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable752(Name) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable752(Name) values('Adam');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable752(Name) values('Chris');
Query OK, 1 row affected (0.26 sec)

使用 select 语句从表中显示所有记录 -

mysql> select *from DemoTable752;

这将生成以下输出 -

+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Carol |
|  3 | Bob   |
|  4 | Mike  |
|  5 | Sam   |
|  6 | Adam  |
|  7 | Chris |
+----+-------+
7 rows in set (0.00 sec)

下面是按自定义值排序的查询 -

mysql> select *from DemoTable752
   order by
      case
         when Id IN (1,2,3) then 1
         else Id
   END,
Name;

这将生成以下输出 -

+----+-------+
| Id | Name  |
+----+-------+
|  3 | Bob   |
|  2 | Carol |
|  1 | John  |
|  4 | Mike  |
|  5 | Sam   |
|  6 | Adam  |
|  7 | Chris |
+----+-------+
7 rows in set (0.00 sec)

更新于: 2019-09-03

110 次浏览

开启你的 职业生涯

完成课程以获取证书

开始
广告