我必须编写一个查询,其中条件参数未知,因为它们是在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
如果无法切换到命名参数,则仍然可以使用相同的技巧,但是您需要为每个可选的参数传递两个参数:如果设置了第二个参数,则该对的第一个参数为
1
,如果第二个参数为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