是否可以在db2的CASE表达式中使用子选择?

时间:2018-01-22 14:45:06

标签: sql db2

我正在尝试在db2数据库上运行以下查询。

SELECT 
    columnA,
    (CASE  
        WHEN columnA NOT IN (SELECT DISTINCT columnC FROM table_2) THEN 1 ELSE 0
    END) AS columnB
FROM
    table_1;

这产生了错误SQL0115 - Comparison operator NOT not valid。如果我用我知道它将产生的值替换子选择,则没有错误。

SELECT 
    columnA,
    (CASE  
        WHEN columnA NOT IN ('ABC', 'EFG') THEN 1 ELSE 0
    END) AS columnB
FROM
    table_1;

是否可以对db2使用CASE表达式的子选择?

1 个答案:

答案 0 :(得分:0)

您的代码应该没问题,但distinct不是必需的:

SELECT columnA,
       (CASE WHEN columnA NOT IN (SELECT columnC FROM table_2) THEN 1 ELSE 0
        END) AS columnB
FROM table_1;

但是,我会使用NOT EXISTS

来编写它
SELECT columnA,
       (CASE WHEN NOT EXISTS (SELECT 1 FROM table_2 t2 WHERE t2.columnC = t1.columnA)
             THEN 1 ELSE 0
        END) AS columnB
FROM table_1 t1;
当子查询返回的任何值为NOT IN时,

NULL将无法正常工作。

您还可以将逻辑移至FROM子句:

SELECT columnA,
       (CASE WHEN t2.columnC IS NOT NULL THEN 1 ELSE 0
        END) AS columnB
FROM table_1 t1 LEFT JOIN
     (SELECT DISTINCT columnC
      FROM table_2
     ) t2
     ON t2.columnC = t1.columnA