Postgres子查询限制

问题描述 投票:0回答:1

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

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 
    '[email protected]' <% 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个回答
2
投票

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

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 '[email protected]' <% coalesce(email1, '')  
    limit 250
  )
  UNION 
  (
    select * 
    from contacts 
    where '26 Ashley Gardens' <% coalesce(address1, '')
    limit 250
)  AS sub
order by score desc;
© www.soinside.com 2019 - 2024. All rights reserved.