Fastest way to update a MySQL table if row exists else insert. More than 2 non-unique keys

后端 未结 1 647
小蘑菇
小蘑菇 2021-01-04 10:02

I have the following table structure:

 CREATE TABLE IF NOT EXISTS `reports` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day` int(11) NOT NULL,
  `uid` int(1         


        
相关标签:
1条回答
  • 2021-01-04 10:22

    just use INSERT...ON DUPLICATE KEY UPDATE

    INSERT INTO reports_adv (day, uid, siteid, cid, visits) 
    VALUES ('$day', '$uid', '$sid', '$cid', 1)
    ON DUPLICATE KEY UPDATE visits=visits+1;
    
    • INSERT ... ON DUPLICATE KEY UPDATE Syntax

    but before anything else, you should define a UNIQUE constraint on the columns.

    ALTER TABLE reports_adv  ADD CONSTRAINT tb_uq UNIQUE (day, uid, siteid, cid)
    
    0 讨论(0)
提交回复
热议问题