- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Concatenate two tables in MySQL with a condition?
To concatenate two tables, UNION ALL in MySQL. Let us create a table −
mysql> create table DemoTable1 ( Id int, FirstName varchar(20) ); Query OK, 0 rows affected (1.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(10,'John'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable1 values(20,'Carol'); Query OK, 1 row affected (0.28 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
Output
+------+-----------+ | Id | FirstName | +------+-----------+ | 10 | John | | 20 | Carol | +------+-----------+ 2 rows in set (0.00 sec)
Create second table.
mysql> create table DemoTable2 ( Id int, FirstName varchar(20) ); Query OK, 0 rows affected (1.22 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(20,'David'); Query OK, 1 row affected (1.28 sec) mysql> insert into DemoTable2 values(40,'Chris'); Query OK, 1 row affected (0.38 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
Output
+------+-----------+ | Id | FirstName | +------+-----------+ | 20 | David | | 40 | Chris | +------+-----------+ 2 rows in set (0.00 sec)
Following is the query to concatenate two tables −
mysql> select *from DemoTable1 where Id=20 union all select *from DemoTable2 where Id=20;
Output
+------+-----------+ | Id | FirstName | +------+-----------+ | 20 | Carol | | 20 | David | +------+-----------+ 2 rows in set (0.43 sec)
- Related Articles
- Concatenate with condition in MongoDB?
- How to select rows with condition via concatenate in MySQL?
- Concatenate columns from different tables in MySQL
- Merge two tables with union in MySQL?
- Concatenate two columns in MySQL?
- MySQL SELECT from two tables with a single query
- MySQL select and insert in two tables with a single query
- MySQL join two tables?
- Insert values in two tables with a single stored procedure call in MySQL
- Concatenate two values from the same column with different conditions in MySQL
- Truncate with condition in MySQL?
- Counting with condition in MySQL?
- Concatenate string with numbers in MySQL?
- Selecting records within a range and with a condition set on two columns in MySQL?
- Can MySQL concatenate strings with ||?

Advertisements