11

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 not null,
    primary key (entryday) );

How can I write a simple query which increments, but creates an necessary?

I tried this - but it is not incrementing (it remains at 1):

REPLACE totals SET total = total + 1, entryday = "08-01-11"

Obviously this could be done in 2 queries quite simply, but it's through JDBC calls and may be called many times, so 1 query would be better.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Nick
  • 531
  • 2
  • 7
  • 14

3 Answers3

29

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.

dkarp
  • 14,483
  • 6
  • 58
  • 65
3

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;
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
-1

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"
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255