Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO .. ON DUPLICATE KEY UPDATE for multiple items

Tags:

mysql

I want to do something like this

INSERT INTO t (t.a, t.b, t.c)  VALUES ('key1','key2','value')  ON DUPLICATE KEY UPDATE  t.c = 'value'; INSERT INTO t (t.a, t.b, t.c)  VALUES ('key1','key3','value2')  ON DUPLICATE KEY UPDATE  t.c = 'value2'; 

t.a and t.b are keys. This all works fine but i get an error on the second insert. With phpMyAdmin a query like this works fine but i'm guessing it's running the queries independently as it prints out the results from that query as comments?

Something like this would be good too but i will need to have different values for each item. I prefer this but i'm not sure how i can change the value on the update for each value.

INSERT INTO t (t.a, t.b, t.c) VALUES ('key1','key2','value'), ('key1','key3','value2') ON DUPLICATE KEY UPDATE t.c = ??? 

The problem is in the question marks, what should i put there so that each insert/update will have the correct value? Obviously if i put a value there all the fields will get that value.

If there is another way of doing an "update if exists, otherwise insert" query on multiple fields with two keys, i'm up for other ideas too. I guess i could run each query separately (like phpMyAdmin?) but it's going to be a lot of queries so i really want to avoid that.

like image 732
Antti Avatar asked Jan 16 '09 15:01

Antti


People also ask

How do I use insert on duplicate key update?

Syntax : INSERT INTO table (column_names) VALUES (values) ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2 ; Along with the INSERT statement, ON DUPLICATE KEY UPDATE statement defines a list of column & value assignments in case of duplicate.

Is insert on duplicate key update Atomic?

So yes it is atomic in the sense that if the data that you are trying to insert will cause a duplicate in the primary key or in the unique index, the statement will instead perform an update and not error out.

How do I update multiple rows at once?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);


1 Answers

Use the VALUES() function

INSERT INTO t (t.a, t.b, t.c) VALUES ('key1','key2','value'), ('key1','key3','value2') ON DUPLICATE KEY UPDATE t.c = VALUES(t.c) 

see http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

like image 130
ʞɔıu Avatar answered Oct 13 '22 09:10

ʞɔıu