Insert into a MySQL table or update if exists

前端 未结 11 2643
再見小時候
再見小時候 2020-11-21 04:27

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:



        
相关标签:
11条回答
  • 2020-11-21 05:05
    INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
    
    INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
    
    REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
    

    All these solution will work regarding your question.

    If you want to know in details regarding these statement visit this link

    0 讨论(0)
  • 2020-11-21 05:11

    In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.

    ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);
    

    And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.

    ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);
    

    Note, just make sure to delete first all the data that has the same name and age value across the other rows.

    DELETE table FROM table AS a, table AS b WHERE a.id < b.id 
    AND a.name <=> b.name AND a.age <=> b.age;
    

    After that, it should trigger the ON DUPLICATE event.

    INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
    name = VALUES(name), age = VALUES(age)
    
    0 讨论(0)
  • 2020-11-21 05:12

    Use INSERT ... ON DUPLICATE KEY UPDATE

    QUERY:

    INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
    name="A", age=19
    
    0 讨论(0)
  • 2020-11-21 05:12

    Try this out:

    INSERT INTO table (id, name, age) VALUES (1, 'A', 19) ON DUPLICATE KEY UPDATE id = id + 1;
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-21 05:21

    Check out REPLACE

    http://dev.mysql.com/doc/refman/5.0/en/replace.html

    REPLACE into table (id, name, age) values(1, "A", 19)
    
    0 讨论(0)
  • 2020-11-21 05:21

    When using batch insert use the following syntax:

    INSERT INTO TABLE (id, name, age) VALUES (1, "A", 19), (2, "B", 17), (3, "C", 22)
    ON DUPLICATE KEY UPDATE
        name = VALUES (name),
        ...
    
    0 讨论(0)
提交回复
热议问题