我正在尝试在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表达式的子选择?
答案 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