我有一个customer_products表,其中包含客户到它正在使用的产品的映射
customer_id product_id
c1 p1
c1 p2
c1 p3
c2 p1
c2 p2
c3 p1
我想让所有使用p2但不使用p3的客户。是否可以在不使用嵌套查询的情况下实现这一目标
我能够解决嵌套查询联接的问题。但是由于嵌套联接太慢,所以我无法获得理想的性能。
使用在hading子句中使用条件聚合的查询,以选择至少购买过一次product_id p2且从未购买过product_id p3的所有客户
select customer_id
from mytable
where product_id in ('p2','p3')
group by customer_id
having count(case when product_id = 'p2' then 1 end) > 0
and count(case when product_id = 'p3' then 1 end) = 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句