3

I have a table with the schema:

storeId varchar(255),
ttl int,
date varchar(255),
bytes bigint(255),
UNIQUE KEY storeId_date_index (storeId, date)

I am wanting to insert a row if it doesn't exist, otherwise update it.

For each duplicate key I hit, I want to sum the old value with the new value. How is this possible with the ON DUPLICATE KEY UPDATE command?

Here is what I have so far:

insert into table (storeId, date, ttl, bytes) 
values 
('477866', '2019-02-05', 54543543, 100),
('6301', '2019-02-05', 54543543, 999999),
('12345', '2019-02-05', 54543543, 999999)
ON DUPLICATE KEY UPDATE
bytes = oldval + newval # sum old value with new value where storeId and date match in the values

1 Answer 1

6

To quote the documentation:

In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement.

I.e.:

INSERT INTO mhytable(storeId, date, ttl, bytes) 
VALUES 
('477866', '2019-02-05', 54543543, 100),
('6301', '2019-02-05', 54543543, 999999),
('12345', '2019-02-05', 54543543, 999999)
ON DUPLICATE KEY UPDATE
bytes = bytes + VALUES(bytes)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.