Doing a WHERE IN on multiple columns in Postgresql

后端 未结 4 1396
醉话见心
醉话见心 2020-12-09 15:11

I have a table \'answers\' with an indexed \'problem_id\' integer column, a \'times_chosen\' integer column, and an \'option\' column that\'s a varchar. Currently the only v

4条回答
  •  独厮守ぢ
    2020-12-09 15:41

    You can do this if you cast the data to an array first:

    UPDATE answers
    SET times_chosen = times_chosen + 1
    WHERE ARRAY[problem_id::VARCHAR,option] IN ('{4509,B}', '{622,C}', ... )
    

    However, this will be incredibly inefficient, as it cannot use indexes. Using a JOIN as suggested by @Frank Farmer is a far better solution:

    UPDATE answers a
    SET times_chosen = times_chosen + 1
    FROM (VALUES (4509,'B'), (622,'C') ...) AS x (id,o)
        WHERE x.id=a.problem_id AND x.o=a.option;
    

提交回复
热议问题