MYSQL:将两个表合并为一个,并使用联合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18597952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:44:03  来源:igfitidea点击:

MYSQL: Merge two tables into one, with union

mysqlunion

提问by user1947863

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

现在我要做的是将这个结果(数据)放入 table3(我已经拥有的一个表,与 table1 和 table2 中的列相同)。

Who can help me?

谁能帮我?

回答by cars10m

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_incrementid-columns. Also You should consider using UNION ALLsince UNIONfilters out duplicate lines and therefore will take longer on large tables.

这样您就可以避免使用auto_incrementid 列的麻烦。你也应该考虑使用UNION ALL因为UNION过滤掉重复的行,因此在大表上需要更长的时间。