当列必须满足 MySQL 中的多个值时,如何选择行?


对此,可以使用带 IN() 的 GROUP BY HAVING 子句。我们先创建一个表 -

mysql> create table DemoTable1885
   (
   FirstName varchar(20),
   Subject varchar(50)
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1885 values('John','MySQL');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1885 values('John','MongoDB');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1885 values('Carol','MySQL');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1885 values('David','Java');
Query OK, 1 row affected (0.00 sec)

使用 insert 命令在表中显示一些记录 -

mysql> select * from DemoTable1885;

这将产生以下输出 -

+-----------+---------+
| FirstName | Subject |
+-----------+---------+
| John      |    MySQL|
| John      |  MongoDB|
| Carol     |    MySQL|
| David     |    Java |
+-----------+---------+
4 rows in set (0.00 sec)

以下是当列必须满足多个值时,选择行的查询

mysql> select FirstName from DemoTable1885
   where Subject IN('MySQL','MongoDB')
   group by FirstName
   having count(*)=2;

这将产生以下输出 -

+-----------+
| FirstName |
+-----------+
| John      |
+-----------+
1 row in set (0.00 sec)

更新时间: 2019 年 12 月 27 日

506 次浏览

开启你的 职业

完成课程以获得认证

开始
广告
© . All rights reserved.