【问题标题】:Postgres subquery limitsPostgres 子查询限制
【发布时间】:2018-02-23 16:45:17
【问题描述】:

我有一个查询,它尝试使用姓名、电话和电子邮件值查找相似的联系人。

select *, ranking function(...) as score from
( select * from contacts where 
    'Dave' <% coalesce(contact_name1, '') 
  UNION
  select * from contacts_index where 
    '9782736623' <% coalesce(phone1, '')   
  UNION
  select * from contacts where 
    'dave_79@gmail.com' <% coalesce(email1, '')  
  UNION 
  select * from contacts where 
    '26 Ashley Gardens' <% coalesce(address1, '')                          
)  AS sub
limit 1000 order by score desc;

我使用限制 1000 来防止在查询非常常见的名称(并且电子邮件、电话、地址为空)的情况下缓慢查询。这导致大量记录满足 where 子句,需要进行排序。

但是,我想将此限制分配给 4 个子查询,否则 1000 个限制可能会被名称子查询用完,并且没有类似电子邮件、电话或地址的记录可以通过。

不幸的是,似乎限制不能在子查询中使用。有谁知道我怎么能做到这一点

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    这是您实际上需要在括号之间放置联合子查询的罕见情况之一:

    select *, ranking function(...) as score 
    from
    ( 
      (
        select * 
        from contacts where  'Dave' <% coalesce(contact_name1, '') 
        limit 250
      )
      UNION
      (
        select * 
        from contacts_index 
        where '9782736623' <% coalesce(phone1, '')   
        limit 250
      )
      UNION
      (
        select * 
        from contacts 
        where 'dave_79@gmail.com' <% coalesce(email1, '')  
        limit 250
      )
      UNION 
      (
        select * 
        from contacts 
        where '26 Ashley Gardens' <% coalesce(address1, '')
        limit 250
    )  AS sub
    order by score desc;
    

    【讨论】:

    • 谢谢你 - 成就了我的一天!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多