So I have a table of users which includes the columns 'user_id' and 'points'.
Now, I want to update multiple rows using the Map/Array [{id: 1, points: 2}, {id: 2, points: 4}, etc...].
And another problem is, I want to ADD to the points values, so building a query-string using a for loop is somewhat more challenging as I need the values beforehand that way.
A (non-working) query (just for understanding the question) would be something like this:
UPDATE users SET points = points + map[i].points WHERE id = map[i].id;
As I mentioned, without the need to add to the value, I would create a String beforehand, and use something like
UPDATE users SET (points) VALUES(x,y,z) WHERE id IN(a, b, c);
But even then, I can't be sure the updates are in the same order as the Map...
edit: I would like to do it in 1 query:)
Any ideas?
EDIT
bagz_man's answer did exactly what I needed. Here it is with the minor syntax errors fixed:
var sql = 'UPDATE users SET points = CASE id';
var i = 0;
var idString='';
map.forEach(function(item){
sql += ' WHEN '+item.id+' THEN points + '+item.points;
idString += item.id.toString();
if(i < map.length-1){
idString +=', ';
}
i++;
});
sql += ' END WHERE id IN('+idString+') ;';