1

I'm able to update my table when mykey (primary key) exists, or insert when mykey does not exist, with this query:

INSERT INTO customers (id, customer_id, page_id, mykey, hits) 
 VALUES 
(NULL, 1, 1, 23, 49) ON DUPLICATE KEY UPDATE hits=hits+49;

Works fine. Now I can't figure out how to add multiple values in one query. What I want is this:

INSERT INTO customers (id, customer_id, page_id, mykey, hits) 
 VALUES 
(NULL, 1, 1, 23, 49) ON DUPLICATE KEY UPDATE hits=hits+49,
(NULL, 2, 2, 56, 11) ON DUPLICATE KEY UPDATE hits=hits+11,
(NULL, 3, 3, 81, 14) ON DUPLICATE KEY UPDATE hits=hits+14;

But that doesn't work. Is it possible to insert or update multiple values like this in one query?

2 Answers 2

1
INSERT INTO customers (id, customer_id, page_id, mykey, hits) 
 VALUES 
(NULL, 1, 1, 23, 49),
(NULL, 2, 2, 56, 11),
(NULL, 3, 3, 81, 14)
ON DUPLICATE KEY UPDATE hits=hits+VALUES(hits);
Sign up to request clarification or add additional context in comments.

1 Comment

Minor syntax error, missing commas after the first two sets of values.
0

Do the ON DUPLICATE KEY UPDATE once at the end:

INSERT INTO customers (id, customer_id, page_id, mykey, hits) 
 VALUES 
(NULL, 1, 1, 23, 49),
(NULL, 2, 2, 56, 11),
(NULL, 3, 3, 81, 14) 
ON DUPLICATE KEY UPDATE hits=hits+VALUES(hits);

2 Comments

Doens't work, because all update rows would have hits=hits+14.
@Aiken Thanks, missed that!

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.