Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: Merge two tables into one, with union

Tags:

mysql

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?

like image 814
user1947863 Avatar asked Sep 03 '13 17:09

user1947863


People also ask

How do you unify two tables?

1. Click on the table you want to drag, then the cross sign will be appeared, then click the cross sign to select the whole table. 2. Press Shift + Alt + Up arrow until the selected table is joined to above one.

Is there any UNION join in MySQL?

Union in MySQLIt joins all the rows in both tables without the duplicate rows. With the UNION operator you can combine the results of multiple SELECT queries into a single result.

How do I merge two tables in a new table in SQL?

The simplest way to combine two tables together is using the keywords UNION or UNION ALL. These two methods pile one lot of selected data on top of the other. The difference between the two keywords is that UNION only takes distinct values, but UNION ALL keeps all of the values selected.


1 Answers

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.

like image 76
Carsten Massmann Avatar answered Oct 06 '22 00:10

Carsten Massmann