有没有更快的方法来选择那些烧坏了东西而且从来没有烧过东西2的用户?

时间:2016-09-06 16:05:27

标签: sql sql-server

我有两张桌子。一个有用户ID,第二个用户ID和他们的硬币。 我尝试选择用户ID(没有欺骗),这些用户ID是dh,而且从来没有thing1

我可以使用这个解决方案:

thing2

但是提出两个查询可能不是最佳解决方案。

我试着写这个:

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的用户ID。)

2 个答案:

答案 0 :(得分:2)

您可以按用户进行分组,然后只选择至少有一次购买过的用户' thing1'从来没有'东西2'

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

答案 1 :(得分:1)

一种方法是使用except

select user_id
  from purchases_tbl
 where productname = 'thing1'
except
select user_id
  from purchases_tbl
 where productname = 'thing2'

这可能(或可能不)与group by having方法一样有效,但它往往会更准确地自我记录您要实现的逻辑。