MySQL INSERT INTO WHERE NOT EXIST

后端 未结 2 1976
孤街浪徒
孤街浪徒 2021-01-17 02:30

I will like to insert into same table if the ip_address for the product_id wasn\'t exist but preferably not to create two separate query. How can I achieve it?

Below

2条回答
  •  长情又很酷
    2021-01-17 03:09

    You can either use INSERT IGNORE or REPLACE or INSERT ... ON DUPLICATE KEY UPDATE ...

    Each requires you to have a unique constraint on product_id, ip_address

    INSERT IGNORE

    INSERT IGNORE INTO products VALUES (null, 111, '8.8.8.8')
    

    will ignore the insert, if entry already exists.

    REPLACE

    REPLACE INTO products VALUES (null, 111, '8.8.8.8')
    

    will perform a delete plus a new insert.

    INSERT ... UPDATE

    INSERT INTO products VALUES (null, 111, '8.8.8.8')
    ON DUPLICATE KEY UPDATE products SET last_modified = NOW()
    

    Will try to insert and if that fails update the existing record.

    In your case I think you should be fine with INSERT IGNORE, however If you want to change other values if the record already exists, INSERT ... UPDATE ... should work well.

    I generally would not recommend to use REPLACE unless you really want a DELETE FROM table WHERE ... plus INSERT INTO TABLE ...

    Update

    This requires (for this example) a unique index for the combination product, ip_address. You can achive this with

    ALTER TABLE products
    ADD UNIQUE INDEX `UIDX_PRODUCT__IP_ADRESS`(product, ipaddress);
    

提交回复
热议问题