我必须编写一个条件参数未知的查询,因为它们是在 jdbc 中动态设置的。这些条件应该是可选的。 我使用h2数据库。 查询是:
select e.event_id,a.attempt_id,a.preferred,a.duration,a.location
from event e,attempt a
where e.user_label=? and e.start_time=?
and e.end_time=? and e.duration_min=?
and e.duration_max=?
and e.event_id=a.event_id
但是除了使用 OR 之外,如何使这些条件可选,因为参数未知?
谢谢!
最佳答案
如果可以switch to named parameters ,您可以将条件更改为检查参数是否为 null
,如下所示:
select e.event_id,a.attempt_id,a.preferred,a.duration,a.location
from event e,attempt a
where
(:ul is null OR e.user_label=:ul)
and (:st is null OR e.start_time=:st)
and (:et is null OR e.end_time=:et)
and (:dmin is null OR e.duration_min=:dmin)
and (:dmax is null OR e.duration_max=:dmax)
and e.event_id=a.event_id
如果您不能切换到命名参数,您仍然可以使用相同的技巧,但您需要为每个可选参数传递两个参数:如果设置第二个,如果省略第二个则为 0
:
select e.event_id,a.attempt_id,a.preferred,a.duration,a.location
from event e,attempt a
where
(? = 1 OR e.user_label=?)
and (? = 1 OR e.start_time=?)
and (? = 1 OR e.end_time=?)
and (? = 1 OR e.duration_min=?)
and (? = 1 OR e.duration_max=?)
and e.event_id=a.event_id
关于java - 如何编写条件可选的sql查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875920/