Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update sql solution to lc problem: No.1398 #1780

Merged
merged 4 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,23 @@ Orders table:

<!-- 这里可写通用的实现逻辑 -->

**方法一:LEFT JOIN + GROUP BY + HAVING**

我们可以用 `LEFT JOIN` 将 `Customers` 表和 `Orders` 表连接起来,然后按照 `customer_id` 进行分组,最后筛选出购买了产品 A 和产品 B 却没有购买产品 C 的顾客。

<!-- tabs:start -->

### **SQL**

```sql
# Write your MySQL query statement below
SELECT
customer_id,
customer_name
SELECT customer_id, customer_name
FROM
Orders
JOIN Customers USING (customer_id)
Customers
LEFT JOIN Orders USING (customer_id)
GROUP BY 1
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0;
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0
ORDER BY 1;
```

<!-- tabs:end -->
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,23 @@ Orders table:

## Solutions

**Solution 1: LEFT JOIN + GROUP BY + HAVING**

We can use `LEFT JOIN` to join the `Customers` table and the `Orders` table, then group them by `customer_id`, and finally filter out the customers who have purchased products A and B but not product C.

<!-- tabs:start -->

### **SQL**

```sql
# Write your MySQL query statement below
SELECT
customer_id,
customer_name
SELECT customer_id, customer_name
FROM
Orders
JOIN Customers USING (customer_id)
Customers
LEFT JOIN Orders USING (customer_id)
GROUP BY 1
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0;
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0
ORDER BY 1;
```

<!-- tabs:end -->
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# Write your MySQL query statement below
SELECT
customer_id,
customer_name
SELECT customer_id, customer_name
FROM
Orders
JOIN Customers USING (customer_id)
Customers
LEFT JOIN Orders USING (customer_id)
GROUP BY 1
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0;
HAVING sum(product_name = 'A') > 0 AND sum(product_name = 'B') > 0 AND sum(product_name = 'C') = 0
ORDER BY 1;