【问题标题】:don't append "and" clause in where condition when column value is null当列值为空时,不要在 where 条件中附加“and”子句
【发布时间】:2018-11-14 21:19:59
【问题描述】:

我有一个查询,当列值为空时,我不想在 where 条件中附加“and”子句,例如

select * from x where x.abc = 'ACTIVE' and x.start_date < sysdate and x.end_date > sysdate

因此,我希望 x.end_date 仅在其值不为 null 时才适用。没有任何存储过程,只是一个简单的查询。

我还想使用标准构建器和谓词将此查询转换为 spring-data jpa 规范。

【问题讨论】:

    标签: sql oracle spring-data-jpa


    【解决方案1】:

    你可以使用or:

    select *
    from x
    where x.abc = 'ACTIVE' and
          x.start_date < sysdate and
          ( x.end_date > sysdate or x.end_date is null );
    

    【讨论】:

      【解决方案2】:

      您可以查看 NVL 功能。

      select * from x
       where x.abc = 'ACTIVE' 
         and x.start_date < sysdate 
         and NVL(x.end_date,sysdate) >= sysdate
      

      【讨论】:

        【解决方案3】:

        并不是说其他​​答案不正确或不好,但我会写这个有点不同,我在这里发布它是希望有人对为什么一种方法可能比另一种更好有一个有趣的评论。

        这是我要写的:

        select * from x
         where x.abc = 'ACTIVE' 
           and sysdate between x.start_date and nvl(x.end_date,sysdate);
        

        对我来说,上面写着:“当前日期必须在记录的有效日期范围内”。

        【讨论】:

          猜你喜欢
          • 2013-12-23
          • 2011-08-12
          • 1970-01-01
          • 2016-11-25
          • 1970-01-01
          • 2021-07-22
          • 1970-01-01
          • 2012-06-28
          • 2015-09-11
          相关资源
          最近更新 更多