For this, you can use GROUP BY HAVING clause.
Let us first create a table −
mysql> create table DemoTable751 ( StudentName varchar(100), SubjectName varchar(100) ); Query OK, 0 rows affected (0.66 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable751 values('John','MySQL'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable751 values('John','MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable751 values('Sam','MySQL'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable751 values('Carol','Java'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable751 values('David','MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable751 values('Carol','MongoDB'); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable751;
This will produce the following output -
+-------------+-------------+ | StudentName | SubjectName | +-------------+-------------+ | John | MySQL | | John | MongoDB | | Sam | MySQL | | Carol | Java | | David | MySQL | | Carol | MongoDB | +-------------+-------------+ 6 rows in set (0.00 sec)
Following is the query to get all the records with two different values in MySQL −
mysql> select StudentName from DemoTable751 group by StudentName having count(SubjectName) > 1;
This will produce the following output -
+-------------+ | StudentName | +-------------+ | John | | Carol | +-------------+ 2 rows in set (0.00 sec)