Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Import an updated structure into a MySQL table without losing its current content?

We use MySQL tables to which we add new fields from time to time as our product evolves. I'm looking for a way to export the structure of the table from one copy of the db, to another, without erasing the contents of the table I'm importing to.

For example say I have copies A and B of a table, and I add fields X,Y,Z to table A. Is there a way to copy the changed structure (fields X,Y,Z) to table B while keeping its content intact?

I tried to use mysqldump, but it seems I can only copy the whole table with its content, overriding the old one, or I can use the "-d" flag to avoid copying data (dumping structure only), but this will create an empty table when imported, again overriding old data.

Is there any way to do what I need with mysqldump, or some other tool?

like image 266
Udi Wertheimer Avatar asked Jan 02 '11 20:01

Udi Wertheimer


People also ask

Which MySQL command is used to modify the existing structure of a table?

ALTER TABLE changes the structure of a table. For example, you can add or delete columns, create or destroy indexes, change the type of existing columns, or rename columns or the table itself.

How can I modify data in MySQL table?

The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ]; table_name. The name of the table to modify.

Which command can be used to add a new column to an existing table in MySQL?

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.


1 Answers

I just had the same problem and solved it this way:

Export the structure of the table to update. Export the structure of the development table.

run this code for the first file "update.sql" needs to be changed according to your exported filename.

cat update.sql|awk -F / '{
 if(match($0, "CREATE TABLE")) {
   { FS = "`" } ; table = $2
 } else {
   if(match($0,"  `")) {
     gsub(",",";",$0)
     print "ALTER TABLE `" table "` ADD" $0
    }
 }
}' > update_alter.sql

run the same command for the second file

cat development.sql|awk -F / '{
 if(match($0, "CREATE TABLE")) {
   { FS = "`" } ; table = $2
 } else {
   if(match($0,"  `")) {
     gsub(",",";",$0)
     print "ALTER TABLE `" table "` ADD" $0
    }
 }
}' > development_alter.sql

run this command to find the differences in the output files

diff --changed-group-format='%<' --unchanged-group-format='' development_alter.sql update_alter.sql > update_db.sql

In the file update_db.sql there will now be the code you are looking for.

like image 188
meles Avatar answered Oct 19 '22 17:10

meles