用函数反转 where 子句,这可能吗?

inverting where clause with function, is it possible?

目前,我正在使用将在相关表中进行搜索的参数进行复杂查询,这非常有效,但如果我需要说 "I want to find people who don't have a certain condition" 之类的内容,我需要编写相同的 where 子句两次:一次用 IN,一次用 NOT IN。有没有办法避免这种情况?类似于 functionX(select id from tablex): boolean

目前我得到的是这样的:

   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 子句。

我觉得比较直接的方法是横向连接:

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);

我觉得你可以写:

WHERE includeparameter1 = TPatient.Id in (select patientid from tdoctorvisit where x ilike parameter1)

因为:

  • includeparameter1 =一个
  • TPatient.Id in (...) = b

所以你有条件:

WHERE (a = true AND b = true) OR (a = false AND b = false)

这与WHERE a = b

相同