简体   繁体   English

MySQL:合并两个表

[英]MySQL: Merging two tables together

Just wondering, if I have two tables that have some common columns (might be in different order though) and some different columns, is there an easy way to merge the two structures together so that both of them would have the same columns? 我只是想知道,如果我有两个表具有一些公共列(尽管顺序可能不同)和一些不同的列,是否有一种简单的方法将两个结构合并在一起,以便它们都具有相同的列?

I tried exporting the structure of both and merging the files together aiming to have a create query that creates a merged table but because the common columns are not in the same order I end up trying to add the same column twice. 我试图导出两者的结构并将文件合并在一起,目的是要创建一个创建合并表的创建查询,但是由于公用列的顺序不同,所以我最终试图两次添加同一列。

Or maybe if there's a query like: 或者,如果有这样的查询:

ALTER TABLE `example` ADD IGNORE...

I think you want a union all query: 我认为您想要一个union all查询:

select col1, col2, col3, NULL as col4, col5
from table1
union all
select col1, col2, col3, col4, NULL as col5
form table2;

You should look at 'JOIN' so if your_table has more records and you need some additional columns from your_second_table and tables are connected by some common_field column in both you can: 您应该查看“ JOIN”,以便如果your_table包含更多记录,并且需要your_second_table一些其他列,并且表中的表都由一些common_field列连接,则您可以:

SELECT t.*, t2.*
FROM your_table t
LEFT JOIN your_second_table t2
ON t.common_field = t2.common_field
  AND t.another_common_field = t2.another_common_field

最终,对我有用的是导出两个表的结构,并将它们的add列查询放在excel列中,然后删除重复项,并使用剩下的唯一查询(这两个表中的唯一列)创建一个新查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM