In MySQL, can I copy one row to insert into the same table?

后端 未结 26 2396
-上瘾入骨i
-上瘾入骨i 2020-11-27 09:56
insert into table select * from table where primarykey=1

I just want to copy one row to insert into the same table (i.e., I want to duplicate an ex

26条回答
  •  孤街浪徒
    2020-11-27 10:26

    Sorry for the necropost but this is what I turned up with google and since I found this helpful but problematic I wanted to contribute an important modification for anyone else who digs this up.

    First off, I'm using SQL Server, not MySQL, but I think it should work similarly. I used Leonard Challis' solution because it was simplest and met the need, however there's a problem with this - if you simply take the PK and increment it by 1 then what happens if you've added other records since the row in question was added. I decided it was best to just let the system handle the autoincrementing of the PK, so I did the following:

    SELECT * INTO #tmpTable FROM Table WHERE primarykey = 1
    --Optionally you can modify one or more fields here like this: 
    --UPDATE #tmpTable SET somefield = newData
    ALTER TABLE #tmpTable DROP COLUMN TicketUpdateID
    INSERT INTO Tickets SELECT * FROM #tmpTable
    DROP TABLE #tmpTable
    

    I believe this would work similarly in MySQL, but I can't test this, sorry

提交回复
热议问题