0

I have a MySQL table like so:

purchases

id | item | price
-----------------
 1 |    1 | 12.07
 2 |    3 | 14.24
 3 |    4 | 13.12
 4 |    2 | 11.28

Where id is the primary key, and item is unique (but not a unique key). Let's say I need to adjust about half the values like so:

purchases

id | item | price
-----------------
 1 |    1 | 12.07
 2 |    3 |  3.24 << changed
 3 |    4 | 13.12
 4 |    2 |  5.92 << changed

And say I have all the item/price pairs that need to be updated. I could write my updates like so:

UPDATE purchases SET price = 3.24 WHERE item = 3;
UPDATE purchases SET price = 5.92 WHERE item = 2;

But say this table was a million rows long, and I needed to update half a million rows. I don't want to run half a million update statements. Is there a way to do this in one query given all the item/price pairs?

I've looked at the ON DUPLICATE KEY syntax, but I don't think that'll work given that item isn't a primary key in my table, even though for this query, I want it to act like one.

1 Answer 1

1

You can insert the keys and new values into a temporary table, join against that in your update query. Like this

update your_table 
join temp_table on your_table.item = temp_table.item
set your_table.price = temp_table.new_price
Sign up to request clarification or add additional context in comments.

2 Comments

I need to do this on a daily basis, so this is not an ideal solution. Cool idea though.
@user3685285, a temporary table has a specific meaning, and the fact that you don't consider this solution perfectly suitable for daily use suggests that you may not be familiar with temp tables. This is exactly how you do what you are trying to do.

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.