The purpose of this is to copy some rows from one environment to another without overwriting existing rows.
Sample DB:
INSERT INTO `school` (school_id,name) VALUES (15,'Middle');
INSERT INTO `class` (class_id,school_id,name) VALUES (12,15,'Sample');
The idea is school_id and class_id are auto-increments and class has a Foreign Key link back to school. But I want to dump just these rows and insert them into another database that already has a school_id of 15.
It might be something that could look like:
INSERT INTO `school` (name) VALUES ('Middle');
INSERT INTO `class` (school_id,name) VALUES (LAST_INSERT_ID(),'Sample');
But that would just be for this simple example. Imagine if I had 50 classes, 25 students in each, and a few hundred grades for each student/class combo. You could see how the LAST_INSERT_ID() might not work without storing it in a series of variables.
What would be the proper tool to do this kind of operation? Can mysqldump do anything this smart?
You can do this:
Find MAX
school_idin the targetschooltable –SELECT MAX(school_id) INTO @max_school_id FROM school;Change all
school_idvalues in source tables (school,class) – add MAXschool_idfrom the previous point –UPDATE school SET school_id = school_id + @max_school_id + 1;It might be very usefull to add
ON UPDATE CASCADEaction to the foreign key, it will help to changeschool_idin the child table automatically, e.g. –Explanation and example:
Create source tables:
Create target tables:
Update source tables, increment id values:
We should update all unique values, in our case we have to update
class_idin theclasstable andschool_idin theschooltable.Find max
class_idfor the TARGETclasstableIncrement all SOURCE
class_idvaluesclass_id + 1012Find max
school_idfor the TARGETschooltableIncrement all SOURCE
school_idvaluesschool_id + 1015That is all. We can dump source tables:
Now we can easily run this script against the target database.