user1947863
user1947863

Reputation: 73

MYSQL: Merge two tables into one, with union

I have to make a table out of two other tables (and use union). The query that works is:

SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

Now what i have to do is put this result(data) into table3 (a table i already have, with the same columns as in table1 and table2).

Who can help me?

Upvotes: 6

Views: 51173

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

INSERT INTO table3 
SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

since you have the same columns in all three of them ...

In a general case you should work with column lists like

INSERT INTO table3 (col1, col2, col3)
SELECT col1, col2, col3 FROM tabel1
UNION
SELECT col1, col2, col3 FROM tabel2

This way you avoid trouble with auto_increment id-columns. Also You should consider using UNION ALL since UNION filters out duplicate lines and therefore will take longer on large tables.

Upvotes: 25

Related Questions