Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two MySQL tables?

Tags:

merge

sql

mysql

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.

like image 618
Steve McLeod Avatar asked Apr 07 '09 12:04

Steve McLeod


People also ask

How do I combine two data tables in SQL?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column.

How do I join two tables in another database in MySQL?

You just need to prefix the table reference with the name of the database it resides in. – Yuval A. Is it possible to join to different DB's, DB1 = mysql & DB2 = PostgreSQL) . Both have few common tables.

Can you combine two tables?

1. Click at anywhere of the table you want to drag, then the cross sign will be appeared, then select the cross sign to select the whole table. 2. Press Ctrl + X to cut the table, then put the cursor at the place of the table you want to insert the cut table, right click to select Merge table from the context menu.


2 Answers

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.

like image 68
fcw Avatar answered Oct 23 '22 04:10

fcw


It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk) select all_columns_except_pk  from table2; 

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

like image 22
Milan Babuškov Avatar answered Oct 23 '22 02:10

Milan Babuškov