简体   繁体   中英

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

INSERT INTO MyGuests (lastname, id)
VALUES ('Doe', 2)

Note:

  1. My primary intention is to update the row

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM