Duplicate / Copy records in the same MySQL table

前端 未结 9 1042
我在风中等你
我在风中等你 2020-12-04 06:27

I have been looking for a while now but I can not find an easy solution for my problem. I would like to duplicate a record in a table, but of course, the unique primary key

相关标签:
9条回答
  • 2020-12-04 06:59

    Alex's answer needs some care (e.g. locking or a transaction) in multi-client environments.

    Assuming the AUTO ID field is the first one in the table (a usual case), we can make use of implicit transactions.

        CREATE TEMPORARY TABLE tmp SELECT * from invoices WHERE ...;
        ALTER TABLE tmp drop ID; # drop autoincrement field
        # UPDATE tmp SET ...; # just needed to change other unique keys
        INSERT INTO invoices SELECT 0,tmp.* FROM tmp;
        DROP TABLE tmp;
    

    From the MySQL docs:

    Using AUTO_INCREMENT: You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

    0 讨论(0)
  • I have a similar issue, and this is what I'm doing:

    insert into Preguntas  (`EncuestaID`, `Tipo` , `Seccion` , `RespuestaID` , `Texto` )  select '23', `Tipo`, `Seccion`, `RespuestaID`, `Texto` from Preguntas where `EncuestaID`= 18
    

    Been Preguntas:

    CREATE TABLE IF NOT EXISTS `Preguntas` (
      `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `EncuestaID` int(11) DEFAULT NULL,
      `Tipo` char(5) COLLATE utf8_unicode_ci DEFAULT NULL,
      `Seccion` int(11) DEFAULT NULL,
      `RespuestaID` bigint(11) DEFAULT NULL,
      `Texto` text COLLATE utf8_unicode_ci ,
      PRIMARY KEY (`ID`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=522 ;
    

    So, the ID is automatically incremented and also I'm using a fixed value ('23') for EncuestaID.

    0 讨论(0)
  • 2020-12-04 07:01

    I needed this as well; my solution was to use SQLYOG (free version) to export the desired record as SQL (creates an insert).

    I then hand edited this to remove the id as this needs to be auto-generated and then copied the insert into SQLYog to execute it. This was painless. I guess plenty of other MySQL GUIs can do this as well.

    This provides me with a record I can use for test purposes on a live system.

    I now have this insert for reuse as well, as the table is rewritten daily.

    0 讨论(0)
提交回复
热议问题