[英]Best practice to update a row if exists otherwise insert [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
I want to know more efficient way to update a row in table, if row not exists it must be inserted. 我想知道一种更新表中行的更有效方法,如果不存在该行,则必须将其插入。
My query is 我的查询是
UPDATE MyGuests SET lastname='Doe' WHERE id=2
When this query is run and there is no row with id=2, a row must be inserted like 运行此查询并且没有id = 2的行时,必须像
INSERT INTO MyGuests (lastname, id)
VALUES ('Doe', 2)
Note: 注意:
My primary intention is to update the row 我的主要目的是更新行
I don't want primary key change when updating a row. 我不希望在更新行时更改主键。
Assuming that id
is your Primary/Unique Key, you can use INSERT..ON DUPLICATE KEY UPDATE
: 假设
id
是您的主键/唯一键,则可以使用INSERT..ON DUPLICATE KEY UPDATE
:
INSERT INTO MyGuests (id, lastname) VALUES (2, 'Doe')
ON DUPLICATE KEY UPDATE lastname = 'Doe'
You can refer this way: 您可以这样引用:
UPDATE MyGuests SET lastname='Doe' WHERE id=2
IF ROW_COUNT()=0
INSERT INTO MyGuests (lastname, id) VALUES ('Doe',2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.