How do I select data from one table only where column values from that table match the column values of another table in MySQL?

MySQLMySQLi Database

For this, you can use subquery along with EXISTS. Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int,
   -> SubjectName varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(111,'MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values(112,'MongoDB');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1 values(113,'Java');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1 values(114,'C');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable1 values(115,'MySQL');
Query OK, 1 row affected (0.23 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+------+-------------+
| Id   | SubjectName |
+------+-------------+
|  111 | MySQL       |
|  112 | MongoDB     |
|  113 | Java        |
|  114 | C           |
|  115 | MySQL       |
+------+-------------+
5 rows in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2
    -> (
    -> FirstName varchar(20),
    -> StudentSubject varchar(20)
    -> );
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Chris','MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2 values('Bob','MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable2 values('Sam','MySQL');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable2 values('Carol','C');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+-----------+----------------+
| FirstName | StudentSubject |
+-----------+----------------+
| Chris     | MySQL          |
| Bob       | MySQL          |
| Sam       | MySQL          |
| Carol     | C              |
+-----------+----------------+
4 rows in set (0.00 sec)

Here is the query to select data from one table only where column values from that table match the column values of another table −

mysql> select Id from DemoTable1
   -> where exists
   -> (
   -> select 1 from DemoTable2
   -> where SubjectName=StudentSubject
   -> );

This will produce the following output −

+------+
| Id   |
+------+
|  111 |
|  114 |
|  115 |
+------+
3 rows in set (0.00 sec)
raja
Published on 11-Dec-2019 06:22:57
Advertisements