Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MySQL SELECT from two tables with a single query
Use UNION to select from two tables. Let us first create a table −
mysql> create table DemoTable1 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) ); Query OK, 0 rows affected (0.90 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1(FirstName) values('Chris') ;
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1(FirstName) values('Adam');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1(FirstName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | Chris | | 2 | Adam | | 3 | Sam | +----+-----------+ 3 rows in set (0.00 sec)
Following is the query to create second table −
mysql> create table DemoTable2( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20) ); Query OK, 0 rows affected (1.75 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2(FirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable2(FirstName) values('Tom');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2(FirstName) values('Bob');
Query OK, 1 row affected (0.50 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Tom | | 3 | Bob | +----+-----------+ 3 rows in set (0.00 sec)
Following is the query to select from two tables using MySQL UNION −
mysql> (select *from DemoTable1) union (select *from DemoTable2) order by FirstName;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 2 | Adam | | 3 | Bob | | 1 | Chris | | 1 | John | | 3 | Sam | | 2 | Tom | +----+-----------+ 6 rows in set (0.00 sec)
Advertisements
