Insert into a MySQL table or update if exists

前端 未结 11 2646
再見小時候
再見小時候 2020-11-21 04:27

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:



        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 05:22

    Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):

    INSERT  live-db.table1
    SELECT  *
    FROM    test-db.table1 t
    ON DUPLICATE KEY UPDATE
            ColToUpdate1 = t.ColToUpdate1,
            ColToUpdate2 = t.ColToUpdate2,
            ...
    

    As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.

    No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.

提交回复
热议问题