我有一个查询,尝试使用姓名,电话和电子邮件值查找类似的联系人。
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限制,并且没有具有类似电子邮件,电话或地址的记录可以通过。
不幸的是,似乎限制不能在子查询中使用。有谁知道我怎么做到这个
答案 0 :(得分: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 '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;