使用单个查询从 MySQL 表中的另一列中按自定义顺序选择一个值

mysqlmysqli database更新于 2025/10/4 9:16:17

为此,您可以使用 IN()。

首先我们创建一个表:

mysql> create table DemoTable727 (
   Name varchar(100),
   Score int
);
Query OK, 0 rows affected (0.88 sec)

使用 insert 在表中插入一些记录 command:

mysql> insert into DemoTable727 values('Chris',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable727 values('Robert',89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable727 values('Carol',94);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable727 values('David',93);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable727 values('Mike',78);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable727 values('Sam',67);
Query OK, 1 row affected (0.22 sec)

使用 select 语句显示表中的所有记录:

mysql> select *from DemoTable727;

这将产生以下输出 -

+--------+-------+
| Name   | Score |
+--------+-------+
| Chris  | 45    |
| Robert | 89    |
| Carol  | 94    |
| David  | 93    |
| Mike   | 78    |
| Sam    | 67    |
+--------+-------+
6 rows in set (0.00 sec)

以下是使用单个查询从 MySQL 表中的另一列中按自定义顺序选择值的查询:

mysql> select Score from DemoTable727 where Name IN('Robert','David','Sam');

这将产生以下输出 -

+-------+
| Score |
+-------+
| 89    |
| 93    |
| 67    |
+-------+
3 rows in set (0.00 sec)

相关文章


有用资源