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;
阅读更多:MySQL 教程
输出结果
+----+--------------+
| 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)