我有两个包含类似信息的表。作为一个最小的例子说我有以下内容:
table1 id|date|info1
table2 id|date|info2
我想将这两个表合并为一个,使其成为
table3 id|date|info1|info2
我尝试了以下内容:
SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date
然后遍历此选择并相应地更新。
它有效,但速度很慢。我想知道是否有更好的方法来做到这一点。
答案 0 :(得分:3)
您可以使用CTAS(Create Table As Select),如下所示:
CREATE TABLE YourMergedTable AS
SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date
MySQL将检测查询产生的字段类型,并相应地创建表结构。
如果您已经有一个表,或者您想要出于任何其他原因明确创建它,您仍然可以插入这样的记录:
INSERT INTO YourMergedTable(ID, Date, Info1, Info2) /* These are the fieldnames in the table */
SELECT table1.id,table1.date,table1.info1,table2.info2
FROM table1 as temp1
JOIN table2 as temp2
ON table1.id=table2.id AND table1.date=table2.date
答案 1 :(得分:0)
这将产生结果为id | date | info1 | info2
SELECT id, date, info1 AS info1, NULL AS info2 FROM table1
UNION
SELECT id, date, NULL AS info1, info2 AS info2 FROM table2
要将结果插入到表3中,您可以执行
INSERT INTO table3
SELECT id, date, info1 AS info1, NULL AS info2 FROM table1
UNION
SELECT id, date, NULL AS info1, info2 AS info2 FROM table2