MySQL “good” way to insert a row if not found, or update it if it is found

后端 未结 6 1518
小蘑菇
小蘑菇 2020-12-08 11:44

Very often, I want to run a query on one of my users where I want a row stored and associated with that user, in a 1-to-1 relationship. So let\'s say (this is just an arbit

相关标签:
6条回答
  • 2020-12-08 11:54

    In Oracle you have Merge.

    No idea on MySql, but the term might give you something else to search.

    0 讨论(0)
  • 2020-12-08 11:58

    This is called an UPSERT (UPdate or inSERT). There are a number of SO questions about it you can search for. See Wikipedia

    EDIT: MySQL 4.1+ supports INSATE (INSert or updATE), which should get you the same thing, as long as you have a primary key. MySQL Manual

    0 讨论(0)
  • 2020-12-08 11:58

    an example of how I have used ON DUPLICATE KEY UPDATE: INSERT INTO registry (name, value) VALUES ('" . $key . "', '" . $val . "') ON DUPLICATE KEY UPDATE value= '" . $val . "'"

    0 讨论(0)
  • 2020-12-08 12:03

    From my other Stack Overflow answer:

    If you want to do this in a single statement, I would recommend using the INSERT ... ON DUPLICATE KEY UPDATE syntax, as follows:

    INSERT INTO table (id, someothervalue) VALUES (1, 'hi mom')
      ON DUPLICATE KEY UPDATE someothervalue = 'hi mom';
    

    The initial INSERT statement will execute if there is no existing record with the specified key value (either primary key or unique). If a record already exists, the following UPDATE statement (someothervalue = 3) is executed.

    This is supported in all versions of MySQL. For more info, see the MySQL Reference Manual page for INSERT ... ON DUPLICATE KEY UPDATE

    0 讨论(0)
  • 2020-12-08 12:11

    I think it's easier to switch it around. Try to insert, then update.

    MySQL specifically has a clause 'ON DUPLICATE KEY'

    INSERT INTO cars (fields) VALUES (values) ON DUPLICATE KEY UPDATE ...

    This of course requires you to have proper unique keys setup.

    0 讨论(0)
  • 2020-12-08 12:15

    You can use "REPLACE INTO" or "INSERT… ON DUPLICATE KEY UPDATE". I believe the second is what you want, but there are situations where REPLACE INTO is convenient.

    0 讨论(0)
提交回复
热议问题