我有一个旧表和一个新表:
CREATE TABLE `old_table` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `col1` varchar(15) DEFAULT NULL, `col2` int(15) DEFAULT NULL, ..., 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;
但是这样会因为重复key而导致错误。我懒得在 SELECT 子句中指定列,因为在实际系统中表有很多列。
解决该问题的最佳方法是什么?
最佳答案
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 - 插入带有 AUTO_INCREMENT 列的 xxx SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565316/