I need to migrate data from one Database to another one, both are on the same local system.
The tables and columns got different names and I mustn't migrate all the Columns from the old Database, so
Select *
doesn't work for me.
INSERT INTO newDatabase.table1(Column1, Column2); SELECT oldDatabase.table1(column1, column2) FROM oldDatabase.table1
but all i got is a #1064 - Syntax Error
What is the error in my Query and How can i fix this ?
Thanks in advance
But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE].
Your query should go like this:
INSERT INTO newDatabase.table1 (Column1, Column2) SELECT column1, column2 FROM oldDatabase.table1;
UPDATE
Since this answer is getting more attention than I even anticipated, I should expand on this answer. First of all, it might not be obvious from the answer itself, but the columns do not need to have the same name. So, following will work too (assuming that the columns exist in their respective tables):
INSERT INTO newDatabase.table1 (Column1, Column2) SELECT SomeOtherColumn, MoreColumns FROM oldDatabase.table1;
Furthermore, they don't even need to be real columns in the table. One of the examples for transforming data that I use quite often is:
INSERT INTO newDatabase.users (name, city, email, username, added_by) SELECT CONCAT(first_name, ' ', last_name), 'Asgard', CONCAT(first_name,'@gmail.com'), CONCAT(first_name,last_name), 'Damir' FROM oldDatabase.old_users;
So, as it might be more obvious now, the rule is, as long as the SELECT query returns same number of columns that INSERT query needs, it can be used in place of VALUES.
INSERT INTO db1.table SELECT * FROM db2.table;
If you want to copy data to same tables of different db.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With