这里是SQL新手。我有一张表,看起来像这样:

我想要获取记录的product_id,它们在表中出现了两次:一次是variant_id X,variant_id Y。在显示的屏幕截图中,结果将是product_id = 5106 (因为它存在两个variant_id = 19607和19608)。
然而,我不知道该怎么做。我尝试使用WHERE variant_id IN(19607,19608)语句,但它返回设置了这些IN之一的任何记录。我还尝试了WHERE variant_id = 19607和variant_id = 19608,但是什么也没有返回(这很容易理解,因为一个记录不能有两个variant_ids)。
我应该使用什么SQL关键字?或者我需要这些的特殊组合?非常感谢你的回答!
发布于 2019-03-01 02:36:48
您可以进行聚合:
select product_id
from table t
where variant_id in (19607, 19608)
group by product_id
having min(variant_id) <> max(variant_id);如果您想要所有列,那么可以使用exists:
select t.*
from table t
where exists (select 1 from table t1 where t1.product_id = t.product_id and t1.variant_id = 19607) and
exists (select 1 from table t1 where t1.product_id = t.product_id and t1.variant_id = 19608);发布于 2019-03-01 02:32:56
我认为这就是你想要的:
select product_id
from t
where variant_id in (19607, 19608)
group by product_id
having count(distinct variant_id) = 2;https://stackoverflow.com/questions/54932097
复制相似问题