MySQL insert on duplicate update for non-PRIMARY key

后端 未结 6 1244

I am little confused with insert on duplicate update query. I have MySQL table with structure like this:

  • record_id (PRIMARY, UNIQUE)
  • person_id (UNIQU
6条回答
  •  伪装坚强ぢ
    2020-12-14 04:38

    You need a query that check if exists any row with you record_id (or person_id). If exists update it, else insert new row

    IF EXISTS (SELECT * FROM table.person WHERE record_id='SomeValue')
        UPDATE table.person 
        SET some_text='new_some_text', some_other_text='some_other_text' 
        WHERE record_id='old_record_id'
    ELSE
        INSERT INTO table.person (record_id, person_id, some_text, some_other_text) 
        VALUES ('new_record_id', 'new_person_id', 'new_some_text', 'new_some_other_text')
    

    Another better approach is

    UPDATE table.person SET (...) WHERE person_id='SomeValue'
    IF ROW_COUNT()=0
        INSERT INTO table.person (...) VALUES (...)
    

提交回复
热议问题