How to make a division in SQL

后端 未结 2 1938
谎友^
谎友^ 2021-01-29 14:53

Let\'s say I have the following table:

CREATE TABLE orders (
    Order_ID int,
    Product_ID int,
    PRIMARY KEY(Order_ID,Product_ID)
);

INSERT INTO orders VA         


        
2条回答
  •  余生分开走
    2021-01-29 15:28

    One way is to select all the lines that correspond to your subset.
    Then group by order, and count how many correspondance you have. If it's equal to the size of your subset, then the order is eligible.

    SELECT orders.order_id
    FROM orders
    WHERE orders.product_id in (2, 3)
    GROUP BY orders.order_id
    HAVING COUNT(1) = 2
    

    Note that this works because you have define PRIMARY KEY(Order_ID,Product_ID), which is a very good idea!

    Fiddle

提交回复
热议问题