Best practice to update a row if exists otherwise insert [duplicate]

眉间皱痕 提交于 2021-01-28 06:33:57

问题


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.


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!