LeetCode MySQL 1398. 购买了产品A和产品B却没有购买产品C的顾客
生活随笔
收集整理的這篇文章主要介紹了
LeetCode MySQL 1398. 购买了产品A和产品B却没有购买产品C的顾客
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
Customers 表:
+---------------------+---------+ | Column Name | Type | +---------------------+---------+ | customer_id | int | | customer_name | varchar | +---------------------+---------+ customer_id 是這張表的主鍵。 customer_name 是顧客的名稱。Orders 表:
+---------------+---------+ | Column Name | Type | +---------------+---------+ | order_id | int | | customer_id | int | | product_name | varchar | +---------------+---------+ order_id 是這張表的主鍵。 customer_id 是購買了名為 "product_name" 產品顧客的id。請你設計 SQL 查詢來報告購買了產品 A 和產品 B 卻沒有購買產品 C 的顧客的 ID 和姓名( customer_id 和 customer_name ),我們將基于此結果為他們推薦產品 C 。
您返回的查詢結果需要按照 customer_id 排序。
查詢結果如下例所示。
Customers table: +-------------+---------------+ | customer_id | customer_name | +-------------+---------------+ | 1 | Daniel | | 2 | Diana | | 3 | Elizabeth | | 4 | Jhon | +-------------+---------------+Orders table: +------------+--------------+---------------+ | order_id | customer_id | product_name | +------------+--------------+---------------+ | 10 | 1 | A | | 20 | 1 | B | | 30 | 1 | D | | 40 | 1 | C | | 50 | 2 | A | | 60 | 3 | A | | 70 | 3 | B | | 80 | 3 | D | | 90 | 4 | C | +------------+--------------+---------------+Result table: +-------------+---------------+ | customer_id | customer_name | +-------------+---------------+ | 3 | Elizabeth | +-------------+---------------+ 只有 customer_id 為 3 的顧客購買了產品 A 和產品 B ,卻沒有購買產品 C 。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/customers-who-bought-products-a-and-b-but-not-c
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
- 注意 having 后面要用聚合函數做判斷,不能having(product_name = 'A')
or
# Write your MySQL query statement below select customer_id, customer_name from Customers wherecustomer_id in (select customer_id from Orders where product_name='A')andcustomer_id in (select customer_id from Orders where product_name='B')andcustomer_id not in (select customer_id from Orders where product_name='C') order by customer_id我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode MySQL 1398. 购买了产品A和产品B却没有购买产品C的顾客的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1135. 最低成本联
- 下一篇: LeetCode 1548. The M