如何在 MySQL 子查询中使用 IN() 返回多条结果?


在 MySQL 中,你可以轻松地返回多个结果,同时也可以通过使用 IN() 的子查询来实现这一目标。首先,我们创建一个表 -

mysql> create table DemoTable1317
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.49 sec)

使用插入命令向表中插入一些记录

mysql> insert into DemoTable1317(Name) values('Chris Brown');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1317(Name) values('John Doe');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1317(Name) values('Adam Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1317(Name) values('John Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1317(Name) values('David Miller');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1317(Name) values('Carol Taylor');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable1317;

输出

+----+--------------+
| Id | Name         |
+----+--------------+
|  1 | Chris Brown  |
|  2 | John Doe     |
|  3 | Adam Smith   |
|  4 | John Smith   |
|  5 | David Miller |
|  6 | Carol Taylor |
+----+--------------+
6 rows in set (0.00 sec)

以下是返回 MySQL 子查询中多个结果的查询 -

mysql> select Name from DemoTable1317
-> where Id IN ( select Id from DemoTable1317);

输出

+--------------+
| Name         |
+--------------+
| Chris Brown  |
| John Doe     |
| Adam Smith   |
| John Smith   |
| David Miller |
| Carol Taylor |
+--------------+
6 rows in set (0.00 sec)

更新于:2019-11-04

303 次浏览

职业生涯起步

完成课程,获得认证

开始
广告