Doing a WHERE IN on multiple columns in Postgresql

后端 未结 4 1395
醉话见心
醉话见心 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;
    
    0 讨论(0)
  • 2020-12-09 15:46

    You can join against a virtual table of sorts:

    SELECT * FROM answers
    JOIN (VALUES (4509, 'B'), (622, 'C'), (1066, 'D'), (4059, 'A'), (4740, 'A')) 
        AS t (p,o)
    ON p = problem_id AND o = option
    

    You can do something similar with UPDATE.

    0 讨论(0)
  • 2020-12-09 15:46

    You're probably looking for the

    SELECT * FROM foo, bar WHERE foo.bob = "NaN" AND bar.alice = "Kentucky";
    

    style syntax. Essentially, you use tablename.rowname to specify what individual field you're looking for. In order to line everything up properly, you add WHERE clauses that make sure the primary keys match:

    ...WHERE foo.primarykey = bar.primarykey
    

    or similar. You'd do well to look up inner joins.

    0 讨论(0)
  • 2020-12-09 16:03

    It should, at least I've done it before in other SQLs.

    Have you tried it? You can test it with SET times_chosen = times_chosen

    0 讨论(0)
提交回复
热议问题