Search code examples
mysqlinsert-update

How to do INSERT ... ON DUPLUCATE KEY UPDATE with old and new rows?


I'd like to add rows to my relationship table, where there will be old rows updated and new rows added. Here is my query (ID is the only key):

INSERT INTO table_rel (ID, player, team, status) VALUES (1,1,1,0), (2,3,1,1) 
ON DUPLICATE KEY UPDATE status=VALUES(status);

What do I put in place of ID in rows that are supposed to be created? eg. (false,2,1,1)


Solution

  • If this is for an AUTO_INCREMENT column, you can supply a NULL value. Easiest way to do that is the keyword NULL

     INSERT INTO table_rel (ID, player, team, status) VALUES
      (1,1,1,0)
     ,(2,3,1,1)
     ,(NULL,6,1,0)
       ^^^^
    

    There's a lot of other expressions you can use to return a NULL value.


    Demonstration supplying NULL keyword for AUTO_INCREMENT column, along with other rows that have a non-NULL value supplied:

    CREATE TABLE foo 
    ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY
    , mi VARCHAR(5)
    ) ENGINE=INNODB;
    ;
    
    INSERT INTO foo (id, mi) VALUES
     (1,'1')
    ,(NULL,'too')
    ;
    -- 2 row(s) affected 
    
    INSERT INTO foo (id, mi) VALUES 
     (1,'one')
    ,(NULL,'three')
    ,(2,'two')
    ON DUPLICATE KEY
    UPDATE mi = VALUES(mi)
    ;
    -- 5 row(s) affected 
    
    SELECT * FROM foo
    ;
    --  id  mi
    -- ---  ------
    --   1  one
    --   2  two
    --   3  three