Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying data from one table to another table. Databases are different and table structure is different

I am looking for a solutions for my MySQL data copying related problem. I have a table TAB1 in a database DB1 that contains some data. Now I want some of these data rows to be migrated to another table TAB2 to some another database DB2.

What would be an ideal way to write such a SQL script for MySQL server. I cannot write java/php program etc because I don't have access to the code base.

Any example links will be helpful. I know this can be done in Oracle via DBLink but how to do it in MySQL.

Thanks

like image 219
Ahsan Avatar asked Nov 22 '25 05:11

Ahsan


2 Answers

insert into db2.table2 (field1,field2,..,fieldN)
select field1,field2,..,fieldN from db1.table1

EDIT. If you need to do an update between two different databases this is the right syntax:

update 
db2.table2 as t2,
db1.table1 as t1
set 
t2.field1 = t1.field1,
t2.field2 = t1.field2,
t2.field3 = t1.field3
where t1.id = t2.id
like image 95
Nicola Cossu Avatar answered Nov 24 '25 19:11

Nicola Cossu


If both databases are on the same server then the easiest way is to use INSERT INTO... SELECT query

INSERT INTO
   database2.table2 (c1, c2, c3)
SELECT
   c2, c4, MD5(c3)  --you can choose only these columns that are needed as well as use functions to convert data to required format if needed
FROM
   database1.table1
like image 38
Mchl Avatar answered Nov 24 '25 19:11

Mchl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!