将两个不同表中的数据合并到一个表中?

时间:2009-09-19 17:39:23

标签: sql join

我有以下两个表:

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) ...

和...

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) ...

我想结束......

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) ...

这看起来很简单,但我似乎无法弄清楚如何做到这一点。这不是一个加入?是吗?

4 个答案:

答案 0 :(得分:5)

UNION条款会对您有所帮助。它将两个或多个结果集合并为一个。

尝试:

SELECT uid, ABC, OtherStuff
FROM Table1

UNION

SELECT uid, DEF, OtherStuff
FROM Table2

UNION

SELECT uid, GHI, OtherStuff
FROM Table3

ORDER BY uid

此主题与UNION ALL运算符有所不同。 UNION会在UNION ALL保留这些行时显式删除重复的行。

除了行中的简单差异之外还有其他结果:要删除重复项,UNION运算符需要对最终结果集进行排序。这是UNION ALL运算符没有遇到的开销。此外,与UNION相比,显式排序操作可能导致UNION ALL收集的结果集在排序顺序上有所不同。我建议您在收集结果集后使用显式ORDER BY语句,以确保您的排序顺序符合您的预期。

另请注意,列数必须与UNION ed的结果集匹配。从OP中不清楚这两个表在它们存储的列数方面有何不同,所以我在两个UNION语句之间做SELECT *时犹豫不决。

答案 1 :(得分:1)

从*中选择*进入table3     (select * from table1 union select * from table2)as tmp

答案 2 :(得分:1)

这将结合两个结果集。为了进行联合,列必须是兼容类型。

(SELECT * FROM table1) UNION (SELECT * FROM table2)

答案 3 :(得分:0)

请记住,union命令将删除重复的行。 如果这不是所需的行为,则需要使用union all。