MySQL insert on duplicate update for non-PRIMARY key

后端 未结 6 1252

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

    I came across this post because I needed what's written in the title, and I found a pretty handy solution, but no one mentioned it here, so I thought of pasting it here. Note that this solution is very handy if you're initiating your database tables. In this case, when you create your corresponding table, define your primary key etc. as usual, and for the combination of columns you want to be unique, simply add

    UNIQUE(column_name1,column_name2,...)
    

    at the end of your CREATE TABLE statement, for any combination of the specified columns you want to be unique. Like this, according to this page here, "MySQL uses the combination of values in both column column_name1 and column_name2 to evaluate the uniqueness", and reports an error if you try to make an insert which already has the combination of values for column_name1 and column_name2 you provide in your insert. Combining this way of creating a database table with the corresponding INSERT ON DUPLICATE KEY syntax appeared to be the most suitable solution for me. Just need to think of it carefully before you actually start using your table; when setting up your database tables.

提交回复
热议问题