MySQL insert on duplicate update for non-PRIMARY key

后端 未结 6 1248

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:27

    How about my approach?

    Let's say you have one table with a autoincrement id and three text-columns. You want to insert/update the value of column3 with the values in column1 and column2 being a (non unique) key.

    I use this query (without explicitly locking the table):

    insert into myTable (id, col1, col2, col3)
    select tmp.id, 'col1data', 'col2data', 'col3data' from
    (select id from myTable where col1 = 'col1data' and col2 = 'col2data' union select null as id limit 1) tmp
    on duplicate key update col3 = values(col3)
    

    Anything wrong with that? For me it works the way I want.

提交回复
热议问题