首页 > 解决方案 > 用函数反转where子句,有可能吗?

问题描述

目前,我正在使用将在相关表中进行搜索的参数进行复杂查询,这非常有效,但是如果我需要说“我想找到没有特定条件的人”之类的话,我需要编写相同的 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 子句。

标签: sqlpostgresqlpostgresql-9.6

解决方案


我想你可以写:

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


推荐阅读