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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5045227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:24:03  来源:igfitidea点击:

postgres: use of CASE and ANY() in WHERE clause

sqlpostgresql

提问by Wells

Is there some way to make this work?

有什么方法可以使这项工作?

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

Unfortunately I can't just do t.tid = CASE WHEN t2.someboolval THEN 1 ELSE 2 ENDbecause I need to match against an array. Is this doable?

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

回答by jny

Use AND/OR. Something like:

使用 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)

Edit: formatted

编辑:格式化

回答by valodzka

You have to change place of ANY:

您必须更改 ANY 的位置:

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)