【问题标题】:inverting where clause with function, is it possible?用函数反转where子句,有可能吗?
【发布时间】:2019-07-04 12:44:28
【问题描述】:

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

【问题讨论】:

    标签: sql postgresql postgresql-9.6


    【解决方案1】:

    我觉得你可以写:

    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一样

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-09-04
        • 2015-08-17
        • 1970-01-01
        • 2016-03-30
        相关资源
        最近更新 更多