sql - 如何在带有 IS NULL 的 WHERE 子句中使用 CASE 语句?

标签 sql oracle oracle11g

这是我的查询,它们不起作用,但我想做这样的事情:

SELECT a_field FROM a_table
WHERE
... 
AND
CASE
WHEN a_value_from_another_query IS NULL THEN a_second_field IS NULL
ELSE a_second_field = a_value_from_another_query
END

或者
SELECT a_field FROM a_table
WHERE
... 
AND
CASE a_value_from_another_query
WHEN NULL THEN a_second_field IS NULL
ELSE a_second_field = a_value_from_another_query
END

或者
SELECT a_field FROM a_table
WHERE
... 
AND
CASE NVL(a_value_from_another_query, 'x')
WHEN 'x' THEN a_second_field IS NULL
ELSE a_second_field = a_value_from_another_query
END

a_value_from_another_query IS NULL ,我要加a_second_field IS NULL到我的 WHERE 子句,当 a_value_from_another_query IS NOT NULL ,我要加a_second_field = a_value_from_another_query到我的 WHERE 子句。我怎样才能做到这一点?

最佳答案

听起来您只是从工具箱中选择了错误的工具。

除非我严重误解了您,否则以下内容:

WHERE
    (a_value_from_another_query IS NULL AND a_second_field IS NULL)
  OR
    (a_value_from_another_query IS NOT NULL AND a_second_field = a_value_from_another_query)

...应该是你想要的。

关于sql - 如何在带有 IS NULL 的 WHERE 子句中使用 CASE 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867917/

相关文章:

sql - 随机页面成本和计划

sql - 基本的 sql 查询——其中前缀 =

sql - Postgres 查询在生产环境中速度较慢,但​​在临时环境和本地环境中都较快

sql - 使用任何联接时重复记录

sql - 如何从 Oracle 中的值列表中进行选择

Mysql 不存在或替代方案

SQL计算列中所有可能数字组合的总和

sql - oracle 10g中如何将列转换成行

sql - 使用查询在 select 子句中指定列名

oracle - 在 Oracle 中的关键字后更改表