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.
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.
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With