How to copy a row and insert in same table with a autoincrement field in MySQL?

后端 未结 13 1054
旧时难觅i
旧时难觅i 2020-11-29 15:55

In MySQL I am trying to copy a row with an autoincrement column ID=1 and insert the data into same table as a new row with

13条回答
  •  庸人自扰
    2020-11-29 16:47

    For a quick, clean solution that doesn't require you to name columns, you can use a prepared statement as described here: https://stackoverflow.com/a/23964285/292677

    If you need a complex solution so you can do this often, you can use this procedure:

    DELIMITER $$
    
    CREATE PROCEDURE `duplicateRows`(_schemaName text, _tableName text, _whereClause text, _omitColumns text)
    SQL SECURITY INVOKER
    BEGIN
      SELECT IF(TRIM(_omitColumns) <> '', CONCAT('id', ',', TRIM(_omitColumns)), 'id') INTO @omitColumns;
    
      SELECT GROUP_CONCAT(COLUMN_NAME) FROM information_schema.columns 
      WHERE table_schema = _schemaName AND table_name = _tableName AND FIND_IN_SET(COLUMN_NAME,@omitColumns) = 0 ORDER BY ORDINAL_POSITION INTO @columns;
    
      SET @sql = CONCAT('INSERT INTO ', _tableName, '(', @columns, ')',
      'SELECT ', @columns, 
      ' FROM ', _schemaName, '.', _tableName, ' ',  _whereClause);
    
      PREPARE stmt1 FROM @sql;
      EXECUTE stmt1;
    END
    

    You can run it with:

    CALL duplicateRows('database', 'table', 'WHERE condition = optional', 'omit_columns_optional');
    

    Examples

    duplicateRows('acl', 'users', 'WHERE id = 200'); -- will duplicate the row for the user with id 200
    duplicateRows('acl', 'users', 'WHERE id = 200', 'created_ts'); -- same as above but will not copy the created_ts column value    
    duplicateRows('acl', 'users', 'WHERE id = 200', 'created_ts,updated_ts'); -- same as above but also omits the updated_ts column
    duplicateRows('acl', 'users'); -- will duplicate all records in the table
    

    DISCLAIMER: This solution is only for someone who will be repeatedly duplicating rows in many tables, often. It could be dangerous in the hands of a rogue user.

提交回复
热议问题