避免双重 - 不在 - 选择搜索

时间:2018-04-12 21:27:00

标签: mysql

我有一个搜索引擎。我不希望被阻止的用户参与此搜索。 我有表格块:

id - autoincrement
user - who is blocking
block - who is blocked

和表用户。 我有这个选择,它工作正常:

select c.nome, c.user, c.id, p.foto from users c 
left join profile_picture p on c.id=p.user
where (c.id not in (select `block` from block where user = '1')) //avoid double block select
and (c.id not in (select `user` from block where block = '1')) //avoid double block select
and (c.user like '%uk%' OR c.nome like '%uk%')

问题是,我可以避免这种双重不进入,首先要避免被阻止的用户进行搜索,而要避免被阻止的用户搜索阻止他的人。我可以避免这两个双块表选择吗?

2 个答案:

答案 0 :(得分:1)

您可以将两个查询合并为一个UNION

select c.nome, c.user, c.id, p.foto 
from users c 
left join profile_picture p on c.id=p.user
where c.id not in 
(
  select `block` as  from block where user = '1'
  union  
  select `user` as block from block where block = '1'
) 
and (c.user like '%uk%' OR c.nome like '%uk%')

答案 1 :(得分:1)

您只能使用JOINs,并且只能使用

中的一个SELECT来执行此操作
select c.nome, c.user, c.id, p.foto 
from users c 
left join profile_picture p on c.id=p.user
left join (select * from block where user='1' or block='1') b1 on b1.user=c.id or b1.block=c.id
where b1.user is not null and b1.block is not null
and (c.user like '%uk%' OR c.nome like '%uk%')