Thursday, November 27, 2014

Copy Table From One Database to Another in MySQL

Want to transfer the data from one MySQL table to another?? It is pretty easy to migrate data from one database to another database.

Copy Table From One Database to Another in MySQL

Copy Table From One Database to Another :-

INSERT INTO `table_two` SELECT * FROM `table_one`;

Use the above code which will copy all rows from table_one into table_two. It is must match the number of columns. It does not matter, If there are different names of all columns. It is enough to have a same column count.

MySQL Copy Table With Different Number of Columns :-

We can copy data where the column is different between the two tables. To complete this,  your SELECT will have to return the right number of columns as INSERT statement is expecting.
Additionally, you can filter which results get transferred by using normal MySQL "SELECT WHERE" syntax as per the below example. Here, we only transfer the records from table one that are LIKE ‘some value’ and limit the transfer to 20 results.

INSERT INTO `table_two` (`column_A`, `column_B`) SELECT `column_C`, `column_D` FROM `table_one` WHERE `column_name` LIKE '%some value%' LIMIT 20;

Note :- Here you will notice I select column_C and column_ D, but I insert it into column_A and column_B. It will work perfectly fine even thought the column names are different. If the column count is the same still you will be fine. 

0 comments:

Post a Comment