我有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“at all?
修改 另外我需要确切地说我正在使用JPA和hibernate,所以查询看起来像这样:
@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);
答案 0 :(得分:0)
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)
;