简体   繁体   中英

MySQL - INSERT INTO xxx SELECT with AUTO_INCREMENT column

I have an old_table and a new_table:

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`;

Then both tables are populated with some values. After that, I want to select some rows from old_table and insert into new_table:

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

But this will cause errors due to duplicate key. I'm too lazy to specify the columns in the SELECT clause, because in the real system the tables have a lot of columns.

What would be the best way to get around the problem?

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;

where

<database> - your database

Select all columns except one in MySQL?

How to insert data from an EXECUTE statement in mySql?

You could probably create a before-insert trigger that tests the existence of the id value and replaces it with the correct new value (or null it out if that works - I don't know if MySQL would barf or give you the next auto-incremented value) if it's a duplicate.

Personally, I don't think I would want this kind of trigger to persist, but if you're just doing a one-time insert you could create the trigger, do the insert, then drop the trigger right after.

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

INSERT INTO 'old_table' SELECT * FROM new_table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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