【问题标题】:how to use Case statement in where clause?如何在 where 子句中使用 Case 语句?
【发布时间】:2017-01-02 22:56:44
【问题描述】:

我有 6 个输入字段,其中 2 个是必填字段。其他 4 个字段是可选的,并且在表中不是空值。我必须将这 6 个值传递给游标查询。 游标(开始日期,结束日期,代码 1,代码 2,代码 3,代码 4) Code1、code2、code3 是表中同一个字段名“X”。 如何在 where 子句中包含这些条件?如果给出了 code1 而其他为 null,则过滤条件应包括 X=code1。同样,如果给出 code1 和 code2,则 X=code1, code2。如果没有给出任何内容,则 X 是要从查询中消除的所有值,而不是 X 过滤条件。

select p,q,r from a,b
where a.f1=b.f2
and a.X=code1 <<if only code1 is passed>>
and a.X in (code1,code2)  <<if both code1 and code2 are passed>>

or 

select p,q,r from a,b
where a.f1=b.f2

<<if no value is passed>>

请帮忙!

【问题讨论】:

  • WHERE子句中使用MySQL CASE并没有什么特别的好处,它与其他语言的工作方式不太一样。
  • 添加一些示例表数据和预期结果(以及格式化文本)。同时标记您正在使用的 dbms。

标签: sql


【解决方案1】:

我想你想要这样的东西:

select p, q, r
from a join
     b
     on a.f1 = b.f2
where a.X in (code1, code2) ;

如果code2NULL,查询仍然有效。因此,您可以添加更多代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 2019-07-14
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    相关资源
    最近更新 更多