简体   繁体   English

MySQL:如何将表中的所有列插入到新表中,而对于不匹配的额外列如何插入NULL?

[英]MySQL: How to insert all columns from table to new table and NULL for extra columns not matched?

Let me explain 让我解释

  • I have a MySQL table [Table A] with 89 Columns and 5 Million rows. 我有一个包含89 Columns5 Million行的MySQL表[Table A]。
  • I have to add 10 new columns (default NULL ) to [Table A]. 我必须在[表A]中添加10 new columns (默认为NULL )。 Currently performing Alter Statement on [Table A] take more than 2 hours. 当前在[表A]上执行Alter语句需要两个多小时。
  • I copied the DDL structure from [Table A] to [copied_Table A] as 我将DDL结构从[表A]复制到[复制表A],如下所示:

    CREATE TABLE copied_table_a LIKE table_a;

  • The I added 10 columns to copied_table_a . 我在copied_table_a添加了10 columns

  • Now I want to insert all data from table_a to copied_table_a as 现在我想将所有数据从table_a插入到copied_table_a

    mysql> INSERT copied_table_a SELECT * FROM table_a; ERROR 1136 (21S01): Column count doesn't match value count at row 1

Question
- What is the best way to get data now to copied_table_a ? -现在将数据获取到copied_table_a的最佳方法是什么?

I suggest that you list all columns, but you can do: 我建议您列出所有列,但是您可以执行以下操作:

INSERT INTO copied_table_a
    SELECT a.*,
           NULL, NULL, NULL, NULL, NULL,
           NULL, NULL, NULL, NULL, NULL
    FROM table_a; 

If you want a quick way to save typing you could make use of the information_schema.columns table : 如果您想要一种快速的方法来保存键入内容,可以使用information_schema.columns表:

select concat("insert into copied_table_a (",
               group_concat(column_name),
               ") select ",
               group_concat(column_name)," from ",table_name)
from information_schema.columns
where table_name = 'table_a';

To generate the SQL for you. 为您生成SQL。 Only really good for a one-off but quite fun to play around with. 一次过真的很不错,但是很有趣。

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

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