create a mysql record if it doesnt exist, else update it

后端 未结 4 1425
猫巷女王i
猫巷女王i 2021-01-27 13:35

I would like to modify this MySQL query to insert the row only if it does not exist. Otherwise, I would like to update the existing row.



        
相关标签:
4条回答
  • 2021-01-27 13:55

    Yes, use the INSERT INTO ... ON DUPLICATE KEY UPDATE syntax.

    http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

    You will need to have a key defined on the table of types UNIQUE or PRIMARY KEY.

    0 讨论(0)
  • 2021-01-27 14:07

    read this url

    http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

    check the database emailformname and leadname are unique

    0 讨论(0)
  • 2021-01-27 14:09

    There is also REPLACE.

    Which will update the existing row or will create a new one if it doesn't exist, also the syntax is similar to INSERT.

    It does exactly what INSERT ... ON DUPLICATE KEY UPDATE does, but I think this approach is more elegant.

    0 讨论(0)
  • 2021-01-27 14:15

    Yeah, use ON DUPLICATE KEY UPDATE

    for that. Here is an example:

    INSERT INTO <table> (<field1>, <field2>) VALUES (<value1>, <value2>)
    ON DUPLICATE KEY UPDATE <field2> = 'update CONTENT';
    

    important is the primary key (underlined in phpMyAdmin table).

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