4

我有一个 old_table 和一个 new_table:

创建表`old_table`(
        `id` bigint(20) NOT NULL AUTO_INCREMENT,
        `col1` varchar(15) 默认为空,
        `col2` int(15) 默认为空,
        ...,
        PREMARY_KEY (`id`)
);

CREATE TABLE `new_table` LIKE `old_table`;

然后两个表都填充了一些值。之后,我想从 old_table 中选择一些行并插入 new_table:

INSERT INTO `old_table` SELECT * FROM `new_table` WHERE col2 > 100;

但这会由于重复键而导致错误。我懒得在 SELECT 子句中指定列,因为在实际系统中,表有很多列。

解决问题的最佳方法是什么?

4

3 回答 3

3
set @sql =  (select concat('insert into new_table SELECT NULL,',
             group_concat(column_name),' from ','old_table') from information_schema.columns
         where table_name = 'old_table' and table_schema = '<database>' and column_name != 'id'
             order by ordinal_position);

prepare stmt1 from @sql;
execute stmt1;
deallocate prepare stmt1;

在哪里

<database> - your database

在MySQL中选择除一列之外的所有列?

如何从 mySql 中的 EXECUTE 语句插入数据?

于 2012-07-19T17:00:20.363 回答
2

您可能可以创建一个插入前触发器来测试该id值的存在并将其替换为正确的新值(如果可行,则将其设为空 - 我不知道 MySQL 是否会拒绝或给您下一个自动递增的值)如果它是重复的。

就个人而言,我认为我不希望这种触发器持续存在,但如果您只是进行一次性插入,您可以创建触发器,执行插入,然后立即放下触发器。

于 2012-07-19T16:38:07.237 回答
-1

我遇到了同样的问题并像这样解决它: - 修改 new_table 的 id 列(删除自动增量和主键,允许 NULL) - 将 new_table 中的所有 ID 设置为 NULL - 现在你可以做

INSERT INTO 'old_table' SELECT * FROM new_table

于 2014-03-28T10:42:48.920 回答