How do I efficiently update multiple rows with particular values for a_id 84, and then all other rows set to 0 for that same a_id?
products
p_id a_id best
111 81 99
222 81 99
666 82 99
222 83 99
111 84 99
222 84 99
333 84 99
111 85 99
222 85 99
Right now I'm doing this:
update products as u set
best = u2.best
from (values
(111, 84, 1),
(222, 84, 2)
) as u2(p_id, a_id, best)
where u2.p_id = u.p_id AND u2.a_id = u.a_id
RETURNING u2.p_id, u2.a_id, u2.best
But this only updates the rows within values as expected. How do I also update rows not in values to be 0 with a_id = 84?
Meaning the p_id of 333 should have best = 0. I could explicitly include every single p_id but the table is huge.
- The values set into
bestwill always be in order from 1 to n, defined by the order ofvalues. - The
productstable has 1 million rows