Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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.

like image 643
Nick Avatar asked Jan 18 '11 19:01

Nick


People also ask

How can insert auto increment value in SQL query?

Obtaining the value of column that uses AUTO_INCREMENT after an INSERT statement can be achieved in a number of different ways. To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function.

How do I increment in MySQL?

Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.

How can check auto increment value in a table?

To know the current auto_increment value, we can use the last_insert_id() function. Firstly, we will create a table with the help of INSERT command. Now, we will see how many records have I inserted into my table with the help of SELECT command. Therefore, the last auto increment is 4.

How does auto increment in MySQL works?

Auto Increment is a function that operates on numeric data types. It automatically generates sequential numeric values every time that a record is inserted into a table for a field defined as auto increment.


2 Answers

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.

like image 157
dkarp Avatar answered Oct 06 '22 20:10

dkarp


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;
like image 34
Joe Stefanelli Avatar answered Oct 06 '22 19:10

Joe Stefanelli