【问题标题】:SQL - how to search for double occuring record with different column?SQL - 如何搜索具有不同列的双发生记录?
【发布时间】:2019-02-28 18:31:03
【问题描述】:

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

我想获取记录的 product_id,它们在表中出现两次:一个带有 variant_id X,variant_id Y。在显示的屏幕截图中,结果将是 product_id = 5106(因为它存在两个 variant_id = 19607 和 19608) .

但是,我不知道该怎么做。我尝试使用语句 WHERE variant_id IN(19607,19608),但它返回任何设置了这些 ID 之一的记录。我也试过 WHERE variant_id = 19607 AND variant_id = 19608,但它什么也没返回(很容易理解,因为一条记录不能有两个 variant_id)。

我应该使用什么 SQL 关键字?或者我需要这些的特殊组合?非常感谢您的回答!

【问题讨论】:

    标签: sql


    【解决方案1】:

    你可以做聚合:

    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);
    

    【讨论】:

      【解决方案2】:

      我认为这是你想要的:

      select product_id
      from t
      where variant_id in (19607, 19608)
      group by product_id
      having count(distinct variant_id) = 2;
      

      【讨论】:

      • 哦,我必须使用“有”关键字!这就是我错过的。非常感谢,它成功了:)
      猜你喜欢
      • 1970-01-01
      • 2015-02-15
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      相关资源
      最近更新 更多