简体   繁体   中英

how to merge two mysql tables with same structure

I have 2 tables with same structure and same id (as primary key) but different data :

具有相同结构但数据不同的两个mysql表

Now, I need to merge them and have something like this :

合并mysql表

It is important to not change id of rows and not insert new records.

How can I do that using a MySQL query ?

Think you just need to performe an UPDATE query with an INNER JOIN of the two table. I assume id columns are realted so

UPDATE table1 a
INNER JOIN table2 b
ON a.id = b.id
SET a.fax = b.fax

Otherwise you can set a new table and take values by join two previous table as follow

INSERT INTO table3 (id, tel, fax) 
SELECT a.id, a.tel, b.fax
FROM table1 a
INNER JOIN table2 b
ON a.id = b.id

First, backup your data. Then, if you only want to end up with one table (and the primary keys match), then try this:

UPDATE `table1`
SET `table1`.`fax` = `table2`.`fax`
WHERE `table1`.`id` = `table2`.`id`;

If that doesn't work, it's a good thing you made a backup.

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM