代码之家  ›  专栏  ›  技术社区  ›  ChrisLively

如何从两个表中的结果中获取ID

  •  0
  • ChrisLively  · 技术社区  · 15 年前

    考虑订单。订单将包含一个或多个行项目。每个行项目都是针对特定产品的。

    给定一个包含两个产品的筛选表,我如何获得订单ID,该订单ID至少包含第二个表中列出的所有产品?

    table Orders(
      OrderId int
    )
    
    table LineItems (
      OrderId int,
      LineItemId int,
      ProductId int
    )
    
    table Filter (
      ProductId int
    )
    

    数据

    Orders
    OrderId
    --------
    1
    2
    3
    
    
    LineItems
    OrderId   LineItemId   ProductId
    -------   ----------   ---------
    1         1            401
    1         2            502
    2         3            401
    3         4            401
    3         5            603
    3         6            714
    
    Filter
    ProductId
    ---------
    401
    603
    

    所需查询结果: 订单号:3

    2 回复  |  直到 15 年前
        1
  •  1
  •   Gavin Miller    15 年前

    戴夫很亲近。首先,必须缩小结果集的范围,使其仅包含与筛选表匹配的项,然后按计数获取结果:

    select orderId 
    from lineitems 
    where ProductId 
      in (select productId from filter)
    group by orderid
    having count(distinct productid) 
      = (select count(distinct productid) from filter)
    

    或者使用连接而不是在:

    select orderId 
    from lineitems li
      inner join filter f on li.productId = f.productid
    group by orderid
    having count(distinct li.productid) 
      = (select count(distinct productid) from filter)
    

    我运行了两个QA,它们的性能相同,但是有了一个合适的数据集,我想连接会更好。

        2
  •  1
  •   davek    15 年前
    select orderid
    from lineitems
    group by orderid
    having count(distinct productid) 
      >= (select count(distinct productid) from filter)
    

    可能有效(不确定 having 术语,因为我不能在家里的盒子上测试它)。