MYSQL INSERT or UPDATE IF

前端 未结 3 977
清酒与你
清酒与你 2020-12-16 06:10

Been looking around the web for a while now and don\'t seem to be able to come across anything similar to what I want. I know it\'s something to do with the way I\'m writing

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 06:41

    First, add a UNIQUE constraint on name, barcode, item, location and price.

    ALTER TABLE  tableX
      ADD CONSTRAINT tableX_UQ
        UNIQUE (name, barcode, item, location, price) ;
    

    Then you can use INSERT INTO ... ON DUPLICATE KEY UPDATE:

    INSERT INTO tableX
      (name, barcode, item, location, price, quantity, date)
    VALUES
      (?, ?, ?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
      quantity = CASE WHEN VALUES(date) > date
                   THEN quantity + VALUES(quantity)        -- add quantity
                   ELSE quantity                           -- or leave as it is
                 END
    , date = CASE WHEN VALUES(date) > date
                   THEN VALUES(date) ;                     -- set date to new date
                   ELSE date                               -- or leave as it is
                 END 
    

    REPLACE could also be used but there are differences in the behaviour (which especially matter if you have foreign keys). For details, see this question “INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE” and the answer by @Bill Kawin which discusses the differences between INSERT IGNORE, INSERT ... ON DUPLICATE KEY and REPLACE.

提交回复
热议问题