1045. Customers Who Bought All Products

Table: Customer

±------------±--------+
| Column Name | Type |
±------------±--------+
| customer_id | int |
| product_key | int |
±------------±--------+
This table may contain duplicates rows.
customer_id is not NULL.
product_key is a foreign key (reference column) to Product table.

Table: Product

±------------±--------+
| Column Name | Type |
±------------±--------+
| product_key | int |
±------------±--------+
product_key is the primary key (column with unique values) for this table.

Write a solution to report the customer ids from the Customer table that bought all the products in the Product table.

Return the result table in any order.

The result format is in the following example.
 

Example 1:

Input:
Customer table:
±------------±------------+
| customer_id | product_key |
±------------±------------+
| 1 | 5 |
| 2 | 6 |
| 3 | 5 |
| 3 | 6 |
| 1 | 6 |
±------------±------------+
Product table:
±------------+
| product_key |
±------------+
| 5 |
| 6 |
±------------+
Output:
±------------+
| customer_id |
±------------+
| 1 |
| 3 |
±------------+
Explanation:
The customers who bought all the products (5 and 6) are customers with IDs 1 and 3.

From: LeetCode
Link: 1045. Customers Who Bought All Products


Solution:

Ideas:
  • COUNT(DISTINCT c.product_key) counts how many different products each customer bought.
  • (SELECT COUNT(*) FROM Product) counts how many products exist in total.
  • If the two counts are equal, that customer bought all products.
Code:
# Write your MySQL query statement below
SELECT c.customer_id
FROM Customer c
GROUP BY c.customer_id
HAVING COUNT(DISTINCT c.product_key) = (SELECT COUNT(*) FROM Product);
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐