为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 SQL 中使用可选的 WHERE 子句?

如何在 SQL 中使用可选的 WHERE 子句?

慕桂英4014372 2023-06-08 14:36:33
我正在尝试在单个 sql 中获取记录。我想使用可选的 WHERE 子句来做到这一点。这是我试过的    @Query(value = "select * from Products p where type = 'L' and active =  1 and ?1 is null or p.pNum =?1", nativeQuery = true)     public List<Products> findAllParties(String productNumber);这没有用。当参数为空时,我想带上所有记录,否则我想只带指定的产品。我怎么做?提前致谢。
查看完整描述

3 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

制作2个单独的方法


    @Query(value = "select * from Products p where type = 'L' and active = 

1 and ?1 is null or p.pNum =?1", nativeQuery = true)

    public List<Products> findAllParties(String productNumber);


    @Query(value = "select * from Products p ", nativeQuery = true)

    public List<Products> findAllParties();


查看完整回答
反对 回复 2023-06-08
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

如果您想要有条件地构建查询,请使用 JPACriteria API或 Spring 的Specifications API.



查看完整回答
反对 回复 2023-06-08
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

select * from Products p where req_param is null or ( type='L' and active=1)

因为如果 req_param 为 null 它将对所有行都为真,因此将带来所有记录。如果 req_param 不为空/空条件“req_param is null”将为 false,并且仅基于“(type='L' and active=1)”返回行


查看完整回答
反对 回复 2023-06-08
  • 3 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信