Home > Database > Mysql Tutorial > body text

How to merge two MySQL tables?

WBOY
Release: 2023-09-17 08:33:07
forward
1175 people have browsed it

如何合并两个 MySQL 表?

To merge two MySQL tables, use the following syntax -

INSERT IGNORE INTO yourTableName1 select *from yourTableName2;
Copy after login

We will create two tables containing some records. After that, the merge process will start using the above syntax.

Create the first table-

mysql> create table MergeDemo1
   -> (
   -> id int,
   -> primary key(id),
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (1.00 sec)
Copy after login

Insert records into the table-

mysql> insert into MergeDemo1 values(1,'John');
Query OK, 1 row affected (0.21 sec)
Copy after login

Display records in the table

mysql> select *from MergeDemo1;
Copy after login
Copy after login

The following is the first table The output of -

+----+------+
| id | Name |
+----+------+
| 1  | John |
+----+------+
1 row in set (0.00 sec)
Copy after login

Now let us create the second table-

mysql> create table MergeDemo2
   -> (
   -> id int,
   -> primary key(id),
   -> Name varchar(200)
   -> );
Query OK, 0 rows affected (0.51 sec)
Copy after login

Insert the records in the second table-

mysql> insert into MergeDemo2 values(2,'David');
Query OK, 1 row affected (0.18 sec)
Copy after login

Display all the records in the second table Record -

mysql> select *from MergeDemo2;
Copy after login

The following is the output of the second table-

+----+-------+
| id | Name  |
+----+-------+
| 2  | David |
+----+-------+
1 row in set (0.00 sec)
Copy after login

The following is the query to merge the two tables.

mysql> INSERT IGNORE
-> INTO MergeDemo1 select *from MergeDemo2;
Query OK, 1 row affected (0.19 sec)
Records: 1 Duplicates: 0 Warnings: 0
Copy after login

Now we use the select statement to check whether the second table data is merged. The query is as follows -

mysql> select *from MergeDemo1;
Copy after login
Copy after login

This is the output showing the merged table -

+----+-------+
| id | Name  |
+----+-------+
| 1  | John  |
| 2  | David |
+----+-------+
2 rows in set (0.00 sec)
Copy after login

The above is the detailed content of How to merge two MySQL tables?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!