MySQL how to do an if exist increment in a single query

后端 未结 3 1446
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 11:19

I just wish to have a table to store a number of events by day.

Given a table:

create table totals (
    entryday date,
    total int(11) default 0 n         


        
相关标签:
3条回答
  • 2021-01-02 11:30

    You probably want ON DUPLICATE KEY:

    INSERT INTO totals (entryday, total)
    VALUES ("08-01-11", 1)
    ON DUPLICATE KEY UPDATE total = total + 1
    

    That'll set the "08-01-11" total to 1 if a row doesn't already exist for that date and increment the total by 1 if it does.

    0 讨论(0)
  • 2021-01-02 11:50

    For MySQL 5.0+, see INSERT ON DUPLICATE KEY UPDATE.

    INSERT INTO totals (entryday, total) VALUES ("08-01-11", 1)
      ON DUPLICATE KEY UPDATE total=total+1;
    
    0 讨论(0)
  • 2021-01-02 11:51

    I'm not sure I understand your question, but maybe this query is your answer :

    update totals set total = total + 1 where entryday = "08-01-11"
    
    0 讨论(0)
提交回复
热议问题