A relational database management system uses SQL MERGE (also called upsert) statements to INSERT new records or UPDATE existing records depending on whether or not a condition matches.在 MySQL 實作語法為 INSERT ... ON DUPLICATE KEY UPDATE
實際用法:
INSERT INTO table (IDX, IPAddr, Msg, Status) VALUES ('1', '127.0.0.1', 'foorbar', 'UNSENT') ON DUPLICATE KEY UPDATE Status = 'SENT'說明:
- 若記錄不存在,則新增一筆 (1, 127.0.0.1, 'foorbar', 'UNSENT')
- 如果原記錄存在,修正更新為 (1, 127.0.0.1, 'foorbar', 'SENT')
實例更新(Jan. 22, 2018):
資料表 daily_transaction 結構 ( idx, date, qty, amount )
- idx 為主鍵自動遞增(AUTO INCREMENT)
- date 為唯一鍵(UNIQUE key)
- qty 代表件數、amount 代表總金額
INSERT INTO daily_transaction (date, qty, amount) //date 是唯一鍵 VALUES('1070122', '168', '368100') ON DUPLICATE KEY UPDATE qty='168', amount='368100';
沒有留言:
張貼留言