MySQL UNION SELECT and IN clause in a single query



Let us first create a table −

mysql> create table DemoTable1    -> (    -> StudentId int,    -> StudentName varchar(20)    -> ); Query OK, 0 rows affected (1.24 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(210,'Adam'); Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ |       210 | Adam        | +-----------+-------------+ 1 row in set (0.00 sec)

Here is the query to create second table −

mysql> create table DemoTable2    -> (    -> StudentId int,    -> StudentName varchar(20)    -> ); Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values(100,'Chris'); Query OK, 1 row affected (0.30 sec)

Display all records from the table using select statement −

mysql>  select * from DemoTable2;

This will produce the following output −

+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ |       100 | Chris       | +-----------+-------------+ 1 row in set (0.00 sec)

Here is the query for MySQL UNION SELECT and IN clause −

mysql> select StudentName from    -> (    -> select StudentId,StudentName from DemoTable1    -> UNION    -> select StudentId,StudentName from DemoTable2    -> ) tbl    -> where StudentId IN(210,100);

This will produce the following output −

+-------------+ | StudentName | +-------------+ | Adam        | | Chris       | +-------------+ 2 rows in set (0.00 sec)
Updated on: 2019-11-11T09:37:50+05:30

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements