Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Replace entire table with another one

Tags:

mysql

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.

like image 569
nikksan Avatar asked Oct 17 '16 15:10

nikksan


People also ask

How does replace into work in MySQL?

REPLACE works exactly like INSERT , except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2. 6, “INSERT Statement”. REPLACE is a MySQL extension to the SQL standard.

How do I duplicate a table in another table?

Right-click the table you wish to duplicate, point to Script Table as, then point to CREATE to, and then select New Query Editor Window. Change the name of the table. Remove any columns that are not needed in the new table. Select Execute to create the new table.


3 Answers

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;
like image 50
aynber Avatar answered Oct 19 '22 06:10

aynber


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;
like image 20
Philipp Avatar answered Oct 19 '22 07:10

Philipp


You can drop and create via select

 DROP Table  db2.your_table ;

 Create table db2.your_table
 select * from db1.your_table;
like image 4
ScaisEdge Avatar answered Oct 19 '22 07:10

ScaisEdge