问题
I have a table tbl
|id|points|
1 15
2 35
3 445
4 42
Now if i have an array like
array (2=>10,3=>825,4=>48)
And i want to change the points so that the tbl
looks like this.
|id|points|
1 15
2 10
3 825
4 48
I can change the values using multiple queries but can anyone show how to do this with one single query ?
回答1:
Use a case statement...
Update tbl
set points = CASE
WHEN ID = 1 then 05
when ID = 2 then 10
when ID = 3 then 825
when ID = 4 then 48 END
Working fiddle: http://sqlfiddle.com/#!9/6cb0d/1/0
回答2:
First you have to upload your array to a temp. table. Let's call it new_list, than you can do something like
UPDATE table as t
SET points = (SELECT points FROM new_list WHERE t.id = new_list.id)
To be honest, I have no clue whether this is running on MySQL so you might need to put some own thoughts into.
As it appears the data is inside an PHP array, I think maybe rendering something like
UPDATE table SET points = $points WHERE id = $id1
UPDATE table SET points = $points WHERE id = $id2
UPDATE table SET points = $points WHERE id = $id3
来源:https://stackoverflow.com/questions/29019317/update-multiple-rows-mysql