如何找到在所有商店出售的产品

How to find product that is sold in all shops

我有一个 table 商店(id,shop_name ,地址),另一个 table 销售(shops_id,product_id,product_name、价格、数量)。我怎样才能展示在所有商店都出售的产品。

我这背后的逻辑是,我计算的商店数量是 10 家,如果一种产品在这 10 家商店都有售,但仍然不起作用。

select product_id, product_name from sales
join shops on sales.shopsid = shops.id
group by(product_id, product_name)
having count(shop_name) = 10;

结果应该是在所有商店出售的产品id和产品名称。

您可以使用聚合,但我认为您需要 count(distinct):

select s.product_id, s.product_name
from sales s
group by s.product_id, s.product_name
having count(distinct s.shop_id) = (select count(*) from shops);
-- The question states: Find the products that were sold in EVERY shop
-- This is equivalent to: Find products for which "There does NOT EXIST a shop that did NOT sell the product"
-- This leads to the double "NOT EXISTS (NOT EXISTS())" solution to relational division.::

SELECT *
FROM product c
WHERE NOT EXISTS (
        -- find a shop that did not sell our product
        SELECT * FROM shop b 
        WHERE NOT EXISTS (
                -- {product X shop} should not exist
                SELECT * FROM sales nx
                WHERE nx.product_id = c.product_id 
                AND nx.shop_id = b.shop_id
                )
        )
        ;