为此,可以使用GROUP BY HAVING子句。
让我们首先创建一个表-mysql> create table DemoTable751 (
StudentName varchar(100),
SubjectName varchar(100)
);
使用插入命令在表中插入一些记录-mysql> insert into DemoTable751 values('John','MySQL');
mysql> insert into DemoTable751 values('John','MongoDB');
mysql> insert into DemoTable751 values('Sam','MySQL');
mysql> insert into DemoTable751 values('Carol','Java');
mysql> insert into DemoTable751 values('David','MySQL');
mysql> insert into DemoTable751 values('Carol','MongoDB');
使用select语句显示表中的所有记录-mysql> select *from DemoTable751;
这将产生以下输出-+-------------+-------------+
| StudentName | SubjectName |
+-------------+-------------+
| John | MySQL |
| John | MongoDB |
| Sam | MySQL |
| Carol | Java |
| David | MySQL |
| Carol | MongoDB |
+-------------+-------------+
6 rows in set (0.00 sec)
以下是查询以获取MySQL中具有两个不同值的所有记录-mysql> select StudentName from DemoTable751
group by StudentName
having count(SubjectName) > 1;
这将产生以下输出-+-------------+
| StudentName |
+-------------+
| John |
| Carol |
+-------------+
2 rows in set (0.00 sec)