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
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
:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.