CASE ... WHEN在Postgresql的WHERE子句中

时间:2017-08-29 14:06:08

标签: sql postgresql

我的查询如下:

SELECT * 
FROM table 
WHERE t1.id_status_notatka_1 = ANY (selected_type)  
 AND t1.id_status_notatka_2 = ANY (selected_place) 

这里我想添加CASE WHEN 所以我的查询是:

    SELECT *  
    FROM table 
    WHERE t1.id_status_notatka_1 = ANY (selected_type)  
      AND t1.id_status_notatka_2    = ANY (selected_place) 
      AND CASE 
            WHEN t2.id_bank = 12 THEN t1.id_status_notatka_4 = ANY (selected_effect) 
         END

但它不起作用。语法很好但是在搜索任何内容时都失败了。所以我的问题是 - 如何在WHERE子句中使用CASE WHEN。简短示例:如果a = 0,则将一些条件添加到WHERE(AND条件),如果不是则不添加(AND条件)

2 个答案:

答案 0 :(得分:8)

不需要CASE EXPRESSION,只需使用OR括号:

AND (t2.id_bank <> 12 OR t1.id_status_notatka_4 = ANY (selected_effect))

如果您真的想要使用案例,这是正确的语法:

AND t1.id_status_notatka_4 = ANY
    CASE WHEN t2.id_bank = 12 
         THEN (selected_effect)
         ELSE  t1.id_status_notatka_4
     END

虽然我从未尝试将CASEANY一起使用,而且我没有postgres来测试它,所以我希望它可以编译。

答案 1 :(得分:1)

可接受的答案有效,但是我想与那些寻求不同答案的人分享意见。多亏了sagi,我提出了以下查询,但是我也想给出一个测试用例。

让我们假设这是表的结构

tbl
id   | type     | status
-----------------------
1    | Student  | t
2    | Employee | f
3    | Employee | t
4    | Student  | f

,我们想选择所有Status ='t'的Student行,但是,我们也希望检索所有Employee行,而不考虑其Status。

如果我们执行SELECT * FROM tbl WHERE type = 'Student' AND status = 't',我们只会得到以下结果,我们将无法获取员工

tbl
id   | type     | status
-----------------------
1    | Student  | t

执行SELECT * FROM tbl WHERE Status = 't'只会得到以下结果,结果得到了Employee Row,但是结果集中没有包含Employee Row,有人会说执行IN可能会起作用,但是,它将给出相同的结果集。 SELECT * FROM tbl WHERE type IN('Student', 'Employee') AND status = 't'

tbl
id   | type     | status
-----------------------
1    | Student  | t
3    | Employee | t

请记住,我们要检索所有Employee行,而不考虑其状态,以执行查询

SELECT * FROM tbl WHERE (type = 'Student' AND status = 't') OR (type = 'Employee')

结果将

table
id   | type     | status
-----------------------
1    | Student  | t
2    | Employee | f
3    | Employee | t