当前,我正在使用参数进行复杂的查询,该参数将在相关表中进行搜索,这非常有效,但是如果我需要说“我想找到没有特定条件的人”之类的话,我需要写两次相同的where子句:一次使用IN,一次使用NOT IN。有办法避免这种情况吗?类似于functionX(从tablex中选择id):布尔值
目前我有这样的东西:
select * from tpatient
where
(includeparameter1 and TPatient.Id in
(select patientid from tdoctorvisit where x ilike parameter1)
)
or (
(includeparameter1 = false) and TPatient.Id not in (
select patientid from tdoctorvisit where x ilike parameter1)
)
能否以某种方式改进下面的查询?
select * from tpatient where
functionX(includeparameter1, TPatient.id,
select patientid from tdoctorvisit where x ilike parameter1)
这将使我的查询小一些,因为我得到了十几个where子句。
答案 0 :(得分:3)
我想你可以写:
WHERE includeparameter1 = TPatient.Id in (select patientid from tdoctorvisit where x ilike parameter1)
因为:
includeparameter1
= a TPatient.Id in (...)
= b 所以您有条件:
WHERE (a = true AND b = true) OR (a = false AND b = false)
这与WHERE a = b
答案 1 :(得分:1)
我认为相对直接的方法是横向联接:
select p.*
from tpatient p cross join lateral
(values (p.Id in (select dv.patientid from tdoctorvisit dv where dv.x ilike parameter1) )
) v(visitflag)
where (includeparameter1 and v.visitflag) or
(not includeparameter1 and not v.visitflag);