postgres:在WHERE子句中使用CASE和ANY()

时间:2011-02-18 18:38:44

标签: sql postgresql

有没有办法让这项工作?

SELECT
*
FROM table t
INNER JOIN othertable t2 USING (tid)
WHERE
t.tid =
CASE
    WHEN t2.someboolval THEN ANY(ARRAY[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
    ELSE ANY(ARRAY[77,66])
END

不幸的是我不能只做t.tid = CASE WHEN t2.someboolval THEN 1 ELSE 2 END,因为我需要匹配一个数组。这可行吗?

2 个答案:

答案 0 :(得分:12)

使用AND / OR。类似的东西:

  SELECT
  *
  FROM table t
  INNER JOIN othertable t2 USING (tid)
  WHERE
     t2.someboolval AND t.tid IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) 
     OR NOT (t2.someboolval) and t.id IN (77,66)

编辑:格式化

答案 1 :(得分:6)

你必须改变任何地方:

SELECT
*
FROM table t
INNER JOIN othertable t2 USING (tid)
WHERE
  t.tid =
  ANY(CASE
    WHEN t2.someboolval THEN ARRAY[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
    ELSE ARRAY[77,66]
  END)