【问题标题】:SQL exclude a where clause if the variable is null or empty如果变量为空或为空,SQL 会排除 where 子句
【发布时间】:2014-11-15 18:08:41
【问题描述】:

我有这样的 SQL (postgresql) 表达式:

select * from table1 t1 left join table2 t2 on t1.id = t2.id where
t1.name = nameVariable and t2.field = fieldVariable;

如果 nameVariable 为 null 或为空,是否有可能不执行“where t1.name = nameVariable " 吗?

编辑 我还需要准确说明我正在使用 JPA 和休眠,所以查询看起来像这样:

@Query(value = " select * from table1 t1 left join table2 t2 on t1.id = t2.id where
    t1.name = :name and t2.field = :fieldName;", nativeQuery=true)
    public List<Test> getTest(@Param("name") String name, @Param("fieldName") String fieldName);

【问题讨论】:

  • 是的。有可能的。顺便说一句:您的左连接通过在 where 子句t2.field = fieldVariable 中引用它来简化为普通连接
  • 您能告诉我如何实现这一目标吗?谢谢

标签: postgresql variables null where


【解决方案1】:
SELECT *
FROM table1 t1 
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE (t1.name = nameVariable OR nameVariable IS NULL)
AND (t2.field = fieldVariable OR t2.field IS NULL OR fieldVariable IS NULL)
   ;

【讨论】:

  • 感谢您的回复!抱歉,我的问题并不完全清楚(检查编辑)。我已经尝试过您的建议(暂时忘记第二个文件,我只是尝试一个)@Query(value = " select * from table1 t1 left join table2 t2 on t1.id = t2.id where t1.name = :name OR :name IS NULL", nativeQuery=true) 并没有起作用,抛出了一个sql异常(输入参数名称为null)
猜你喜欢
  • 2012-07-16
  • 2012-12-25
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多