How can I merge two MySQL tables?

Steve McLeod picture Steve McLeod · Apr 7, 2009 · Viewed 187.3k times · Source

How can I merge two MySQL tables that have the same structure?

The primary keys of the two tables will clash, so I have take that into account.

Answer

fcw picture fcw · Apr 7, 2009

You can also try:

INSERT IGNORE
  INTO table_1 
SELECT *
  FROM table_2
     ;

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.

Alternatively,

REPLACE
   INTO table_1
 SELECT *
   FROM table_2
      ;

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.