Mysql

“重複鍵更新”插入中提到的所有非鍵欄位

  • July 16, 2021

如何更新該部分中提到的欄位值insert而不在該部分中再次列出它們on duplicate key update

insert into tablename set keyname = 'keyvalue',
   fieldname = 'fieldvalue'
   . . .
   on duplicate key update
       updatecounter = updatecounter + 1
       fieldname = 'fieldvalue'
       . . .;

您可以使用以下VALUES(column)功能:

insert into tablename set keyname = 'keyvalue',
   fieldname = 'fieldvalue'
   . . .
   on duplicate key update
       updatecounter = updatecounter + 1,
       fieldname = VALUES(fieldname)
       . . .;

雖然上述方法仍然有效,但它在 MySQL 版本 8.0.20 中已被棄用,並且將來可能會被刪除。如MySQL 文件中所述,執行此操作的新方法:INSERT … ON DUPLICATE KEY UPDATE 語句是:

insert into tablename set keyname = 'keyvalue',
   fieldname = 'fieldvalue'
   . . .
   AS new        -- adding a table alias for the set
                 -- of values to be on inserted
   on duplicate key update
       updatecounter = updatecounter + 1,  -- refers to existing table value
       fieldname = new.fieldname           -- refers to above set
       . . .;

引用自:https://dba.stackexchange.com/questions/10336