tags:

views:

295

answers:

4

I have the following two tables:

uid   | ABC   | ... (bunch of other stuff) ...
1     | val 1 | ... (bunch of other stuff) ...
2     | val 2 | ... (bunch of other stuff) ...
3     | val 3 | ... (bunch of other stuff) ...

and...

uid   | DEF   | ... (bunch of other stuff) ...
4     | val 4 | ... (bunch of other stuff) ...
5     | val 5 | ... (bunch of other stuff) ...
6     | val 6 | ... (bunch of other stuff) ...

I want to end up with...

uid   | text  | ... (bunch of other stuff) ...
1     | val 1 | ... (bunch of other stuff) ...
2     | val 2 | ... (bunch of other stuff) ...
3     | val 3 | ... (bunch of other stuff) ...
4     | val 4 | ... (bunch of other stuff) ...
5     | val 5 | ... (bunch of other stuff) ...
6     | val 6 | ... (bunch of other stuff) ...

This looks so simple, but I just can't seem to figure out how to do this. It's not a join? Is it?

+1  A: 

select * into table3 from (select * from table1 union select * from table2) as tmp

ennuikiller
Let's hope bunch of other stuff's have the same schema.
Zed
+1  A: 

This will union both result sets. In order to do a union the columns must be of compatible types.

(SELECT * FROM table1) UNION (SELECT * FROM table2)
Ben S
+3  A: 

The UNION clause will help you here. It combines two or more result sets into one.

Try:

SELECT uid, ABC, OtherStuff
FROM Table1

UNION

SELECT uid, DEF, OtherStuff
FROM Table2

UNION

SELECT uid, GHI, OtherStuff
FROM Table3

ORDER BY uid

There is a variation on this theme with the UNION ALL operator. UNION will explicitly remove duplicate rows while UNION ALL retains them.

This has ramifications beyond the simple difference in rows: to remove duplicates the UNION operator needs to sort the final result set. This is overhead the UNION ALL operator does not experience. Moreover, the explicit sort operation may cause a result set collected by UNION to differ in sort order when compared to UNION ALL. I suggest you use an explicit ORDER BY statement after the result set is collected to ensure your sort order is as you intend it to be.

Please also be aware that the number of columns must match in the result sets being UNIONed. It's not clear from the OP how the two tables differ in terms of the number of columns they store, and so I am hesitant to do a UNION between two SELECT * statements.

David Andres
If you want to create a real table from this, the exact statement depends on the database you're using. On most, it's "create table foo as select uid, ABC..."
KingPong
@KingPong: I took the OP to mean that he/she wanted a single result set, not necessarily a real table. I've posted a comment to the OP because you could be right.
David Andres
A: 

Keep in mind that the union command will remove duplicate rows. If that is not desired behavior, you want to use union all instead.

Chi