是否可以将一个 mysql 表的列(结构和内容)追加到另一个表中?
我想将一个 mysql 表的结构和内容复制到另一个表,将该表的所有列和值添加到另一个表中已有的列和值中。
我可以手动执行此操作,但由于我正在谈论大量列,因此如果有某种 ALTER 语句来帮助我执行此操作,那就太好了。
编辑:
为了更好地解释自己:
我首先需要将表 B(column_name、data_type)中包含的列添加到表 A(它已经有自己的一组列)。完成后,我可以复制内容,这很容易。
我想真正的问题是:有没有办法将表 B 中包含的列添加到另一个拥有自己的列的表(表 A)中?
I would like to copy the structure and the content of one mysql table to another, adding all of the columns and values of that table to the already existing ones in the other table.
I could do it manually, but since I'm talking about a large amount of columns, it would be great if there were some sort of ALTER statement to help me do that.
EDIT:
To explain myself better:
I first need to add the columns contained in table B (column_name, data_type) to table A (which already has its own set of columns). Once that is done, I can copy the content, which is easy.
I guess the real question is: is there a way to add the columns contained in table B to another table (table A) which has columns of its own?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了构建 Flavianatill 的第二个解决方案,在我看来,不需要导出/导入步骤。如果我正确理解了这个问题,下面的一行应该可以解决。
抱歉,我本想将此放在评论中,但我缺乏声誉!
To build on flavianatill's second solution, it seems to me that the export/import step is not needed. If I understand the problem correctly, the following one-liner should do it.
Sorry, I would have put this in a comment but I lack the reputation!
这会将所有数据从源表复制到目标表。您可以指定哪些列应该转到哪些列。通过更改 targetColumn.. 和 sourceColumn... 的名称,
您还可以通过执行
EDIT 创建 sourceTable 一种将所有数据从 sourceTable 提取到 targetTable 的方法,但是如果存在 targetTable,则删除它
EDIT 如果您需要保留旧数据,您可能需要重新映射它,但您可以合并到其他表中,
但这可能需要 ON DUPLICATE KEY UPDATE ..... 逻辑,或者简单地在第二个 if 上 INSERT IGNORE你很高兴扔消除任何主键/唯一键冲突的行。这假设您有要复制的 sourceTable 并与 oldTargetTable 中的数据合并。表 targetTable 只是一个临时名称。
如果您想更喜欢旧表中的数据,那么只需交换执行插入的顺序即可
This will copy all data from a source table to a target table. You can specify which columns should go to which. by changing the names of targetColumn.. and sourceColumn....
You can also create sourceTable by doing
EDIT A method to pull all data from sourceTable to targetTable, however removing targetTable if it exists
EDIT If you need to keep old data, you may need to remap it but you can merge in other tables
This will however potentially either require ON DUPLICATE KEY UPDATE ..... logic, or simply INSERT IGNORE on the second if you are happy throwing away any PRIMARY/UNIQUE key conflicting rows. This assumes you have sourceTable you want to copy and merge with data from oldTargetTable. The table targetTable is just a temporary name.
If you wanted to prefer data from the old table then just swap the order you perform the INSERTs of course