简体   繁体   English

合并两个MySQL表

[英]Merging two MySQL tables

I need to merge any missing rows in a production mysql database from a backup database on restored to the same machine. 我需要从恢复到同一台机器上的备份数据库中合并生产mysql数据库中的所有缺失行。

How can I do this whilst preserving the original primary key id's which are auto increment. 如何在保留自动递增的原始主键ID的同时执行此操作。

You can try: 你可以试试:

INSERT IGNORE INTO table_1 SELECT * FROM table_2;

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys. 这允许table_1中的行取代table_2中具有匹配主键的行,同时仍插入具有新主键的行。

Alternatively, 或者,

REPLACE INTO table_1 SELECT * FROM table_2;

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys. 将使用来自表_2的相应行更新表_1中已经存在的行,同时插入具有新主键的行。

--create a backup just in case
CREATE TABLE table_prod_sav SELECT * FROM table_prod;

--insert the missing rows
INSERT INTO table_prod (id, field) 
    SELECT b.id, b.field 
    FROM table_backup b LEFT JOIN table_prod p ON b.id = p.id
    WHERE p.id IS NULL;

--Check consistency...

--DROP TABLE table_prod_sav;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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