How to merge MySQL results?


To merge, use simple join. Following is the syntax −

select
aliasName1.yourColumnName1,
aliasName1.yourColumnName2,
.
.
.N
aliasName2.yourColumnName1
from yourTableName1 aliasName1
.
.
.
N
join
yourTableName2 aliasName2
on yourCondition;

Let us create a table −

mysql> create table demo8
−> (
−> id int,
−> name varchar(20)
−> );
Query OK, 0 rows affected (1.77 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo8 values(100,'John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo8 values(101,'Mike');
Query OK, 1 row affected (0.16 sec)

mysql> insert into demo8 values(102,'Bob');
Query OK, 1 row affected (0.15 sec)

Display records from the table using select statement −

mysql> select *from demo8;

This will produce the following output −

+------+------+
| id   | name |
+------+------+
| 100  | John |
| 101  | Mike |
| 102  | Bob  |
+------+------+
3 rows in set (0.00 sec)

Following is the query to create second table −

mysql> create table demo9
−> (
−> id int,
−> age int
−> );
Query OK, 0 rows affected (1.90 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo9 values(100,27);
Query OK, 1 row affected (0.09 sec)

mysql> insert into demo9 values(101,24);
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo9 values(102,28);
Query OK, 1 row affected (0.29 sec)

Display records from the table using select statement −

mysql> select *from demo9;

This will produce the following output −

+------+------+
|  id  | age  |
+------+------+
|  100 | 27   |
|  101 | 24   |
|  102 | 28   |
+------+------+
3 rows in set (0.00 sec)

Following is the query to merge results −

mysql> select tbl1.id,tbl1.name,tbl2.age
−> from demo8 tbl1
−> join
−> demo9 tbl2
−> on tbl1.id=tbl2.id;

This will produce the following output −

+------+------+------+
|   id | name | age  |
+------+------+------+
|  100 | John |   27 |
|  101 | Mike |   24 |
|  102 | Bob  |   28 |
+------+------+------+
3 rows in set (0.00 sec)

Updated on: 19-Nov-2020

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements