Getting data from two different tables into one table?
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 finish ...
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) ...
It looks so simple, but I just can't figure out how to do it. Is this not a connection? It?
source to share
Suggestion UNION
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 an operator UNION ALL
. UNION
will explicitly remove duplicate lines, but UNION ALL
keep them.
This has implications beyond the simple difference in strings: to remove duplicates, the operator UNION
must sort the final result set. This overhead is UNION ALL
not incurred by the operator . Moreover, an explicit sorting operation may cause the result set collected UNION
to be different in sort order compared to UNION ALL
. I suggest you use an explicit operator ORDER BY
after collecting the result set to ensure that the sort order is as you intend it.
Also remember that the number of columns must match in UNION
ed result sets . It is not clear from the OP how the two tables differ in the number of columns they store, and so I hesitate to make UNION
between the two statements SELECT *
.
source to share