Mysql – Sync Data Without Replication

MySQL

I have a database server I am using an old dump from to restore due to the need of older records that must be brought back. I also need to sync to this database the new entries from the current database server. How would I accomplish this?

Best Answer

First step - take a backup of both databases (and other files my.cnf &c.)

Second step - you have your mysqldump of your old database.

Third step - edit the old mysqldump file and change the line

CREATE DATABASE old_database_name (may have backticks around name - also I'm assuming that old_database_name is the same as the current_database_name).

to

CREATE DATABASE staging (or name of your choice, but not one that already exists in the current server schemas - SHOW SCHEMAS; will show you this information.

Fourth step - Using the MySQL client (or MySQL Workbench), create an empty schema on the current database also called staging (CREATE SCHEMA staging;)

Fifth step - "restore" the staging database to the current server, using the instructions from here.

In this case, it will be

mysql -u root -p[root_password] staging < old_dumpfilename.sql

So, you now have the current and old databases on the current server, BUT in different schemas.

Sixth step - Your main worry now is how to resolve any conflicts of PRIMARY KEYs.

You can check this by running

SELECT staging.old_table_PK from staging.old_staging_table_name 
WHERE staging.old_table_PK 
IN (SELECT current.current_table_PK FROM current.curent_table_name);

You need to specify the schema name because you are running cross schema queries. The above query will give you any records in both tables which have the same PRIMARY KEY. It will be up to you to resolve any conflicts using your system's logic.

Perform this query for all tables in your current database.

Seventh step - If there are no conflicts, then perform

INSERT INTO current.current_table_name SELECT * from staging.staging_table_name;

This should get you most of the way there. There may be typos in my answer, since I didn't have suitable data to perform a large scale check - but you can do any necessary testing yourself.

REMEMBER - BACKUP before you MESSUP!