本文介紹了插入 MySQL 表或更新(如果存在)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想向數據庫表中添加一行,但如果存在具有相同唯一鍵的行,我想更新該行.
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.
例如:
INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
假設唯一鍵是ID
,在我的數據庫中,有一行ID = 1
.在這種情況下,我想用這些值更新該行.通常這會出錯.
如果我使用 INSERT IGNORE
它會忽略錯誤,但它仍然不會更新.
Let’s say the unique key is ID
, and in my Database, there is a row with ID = 1
. In that case, I want to update that row with these values. Normally this gives an error.
If I use INSERT IGNORE
it will ignore the error, but it still won’t update.
推薦答案
使用 INSERT ... ON DUPLICATE KEY UPDATE
查詢:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
這篇關于插入 MySQL 表或更新(如果存在)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!