How to select row when column must satisfy multiple value in MySQL?


For this, you can use GROUP BY HAVING clause along with IN(). Let us first create a table −

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

Insert some records in the table using insert command −

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)

Display some records in the table using insert command −

mysql> select * from DemoTable1885;

This will produce the following output −

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

Here is the query to select row when column must satisfy multiple value:

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

This will produce the following output −

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

Updated on: 27-Dec-2019

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements