问题
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
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.
回答1:
Assuming that id
is your Primary/Unique Key, you can use INSERT..ON DUPLICATE KEY UPDATE:
INSERT INTO MyGuests (id, lastname) VALUES (2, 'Doe')
ON DUPLICATE KEY UPDATE lastname = 'Doe'
回答2:
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)
来源:https://stackoverflow.com/questions/53312432/best-practice-to-update-a-row-if-exists-otherwise-insert