15

I am trying to achieve this. Say I have a two databases - db1 , db2. They each have a table called tb , the table structure is the same for both however, the records are different. Is there any elegant way I can replace all records inside db2.tb with the records from db1.tb. I think I can achieve this with php , but I`m looking for an elegant way.

2
  • 1
    Just blindly replace the records, or do some fields determine/allow you to decide which data should be replaced? eg: replacing matching ID's etc... Are there constraints on the tables? Indexes that are likely to require a table rebuild? Define "elegant way"... Commented Oct 17, 2016 at 15:09
  • I think OP wants an in db solution rather than do it thru PHP. @nikksan Did you try stackoverflow.com/questions/22912167/… Commented Oct 17, 2016 at 20:53

3 Answers 3

18

You can TRUNCATE (if you want to remove all existing data in db2), then INSERT:

TRUNCATE db2.tb;
INSERT INTO db2.tb SELECT * FROM db1.tb;
Sign up to request clarification or add additional context in comments.

1 Comment

One advantage of this method, is that since the table column structure is the same, the primary key (auto increment etc) should already be set and you wouldn't need to ALTER the table to set that back up.
4

You can drop and create via select

 DROP Table  db2.your_table ;

 Create table db2.your_table
 select * from db1.your_table;

2 Comments

Don't forget If Exists even though we assume it shold be there.
And do note, this does not copy the primary key value, you need to do an Alter statement and reset the primary key settings (Auto increment etc)
1

You can use sql to truncate one table and then insert the data from the other table into it.

Put it into a transaction to keep it safe. http://dev.mysql.com/doc/refman/5.7/en/sql-syntax-transactions.html

TRUNCATE test.stuff;
INSERT INTO test.stuff SELECT * FROM testdb.stuff;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.