我有两个表。一个有用户id,另一个有用户id和他们买的东西。我试图选择购买thing1
而从未购买thing2
的用户ID(没有欺骗)。
我可以使用这个解决方案:
select distinct usr_id
from purchases_tbl
where productname = 'thing1'
and usr_id not in (select usr_id
from purchases_tbl
where productname = 'thing2');
但是进行两次查询可能不是最好的解决方案。
我试着写这个:
select acc.usr_id
from accounts acc
inner join purchases_tbl ptbl
on acc.usr_id = ptbl.usr_id
and ptbl.productname = 'thing1'
where ptbl.productname != 'thing2'
但似乎where
子句根本没有作用(结果仍然包含购买thing2
的用户id)。
您可以按用户分组,然后只取至少一次购买过'thing1'而从未购买过'thing2'的用户
select usr_id
from purchases_tbl
group by usr_id
having sum(case when productname = 'thing1' then 1 else 0 end) > 0
and sum(case when productname = 'thing2' then 1 else 0 end) = 0
一种方法是使用except
select user_id
from purchases_tbl
where productname = 'thing1'
except
select user_id
from purchases_tbl
where productname = 'thing2'
这可能(也可能不是)像group by
having
方法一样有效,但它倾向于更准确地说明您想要实现的逻辑。