Concatenate columns from different tables in MySQL


You can use CONCAT(). Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.90 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1 values('David');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Chris     |
| David     |
+-----------+
2 rows in set (0.00 sec)

Here is the query to create the second table −

mysql> create table DemoTable2
   -> (
   -> LastName varchar(20)
   -> );
Query OK, 0 rows affected (0.95 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Brown');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable2 values('Miller');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2;

This will produce the following output −

+----------+
| LastName |
+----------+
| Brown    |
| Miller   |
+----------+
2 rows in set (0.00 sec)

Here is the query to concatenate column from different tables −

mysql> select concat(tbl1.FirstName,' ',tbl2.LastName) from DemoTable tbl1
   -> left join DemoTable2 tbl2
   -> on tbl2.LastName='Brown' or tbl2.LastName='Miller';

This will produce the following output −

+------------------------------------------+
| concat(tbl1.FirstName,' ',tbl2.LastName) |
+------------------------------------------+
| Chris Brown                              |
| David Brown                              |
| Chris Miller                             |
| David Miller                             |
+------------------------------------------+
4 rows in set (0.04 sec)

Updated on: 13-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements