LeetCode刷题-数据库(MySQL)-1083. Sales Analysis II

1082. Sales Analysis II

一、题目描述

Table: Product

Column Name Type
product_id int
product_name varchar
unit_price int

product_id is the primary key of this table.

Table: Sales

Column Name Type
seller_id int
product_id int
buyer_id int
sale_date date
quantity int
price int

This table has no primary key, it can have repeated rows.
product_id is a foreign key to Product table.

Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.

The query result format is in the following example:

Product table:

product_id product_name unit_price
1 S8 1000
2 G4 800
3 iPhone 1400

Sales table:

seller_id product_id buyer_id sale_date quantity price
1 1 1 2019-01-21 2 2000
1 2 2 2019-02-17 1 800
2 1 3 2019-06-02 1 800
3 3 3 2019-05-13 2 2800

Result table:

buyer_id
1

The buyer with id 1 bought an S8 but didn’t buy an iPhone. The buyer with id 3 bought both.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sales-analysis-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、思路分析

Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.
本题要求找出所有购买了“S8”而不是“iPhone”的消费者。需要注意的有以下几点:

  1. buyer_id 与 product_name 不在同一张表中,所以需要对表Sales与表Product进行表连接。因表Sales中的每一行有效数据必然对应一个产品,所以直接使用内连接(JOIN)即可。
  2. 在发现题目问法为"是……而不是…… "时,一般情况下考虑使用NOT IN语句,即利用子查询找出需要排除的选项,然后通过NOT IN语句将主查询中不符合题意的部分排除出去。
  3. 最后需要注意的使用DISTINCT去重。

三、代码实现

SELECT DISTINCT
    buyer_id
FROM
    Sales as a 
JOIN
    Product as b 
ON
    a.product_id = b.product_id
WHERE
    b.product_name = 'S8'
AND 
    a.buyer_id 
NOT IN
    (
        SELECT DISTINCT 
            buyer_id
        FROM
            Sales as a 
        JOIN
            Product as b 
        ON 
            a.product_id = b.product_id
        WHERE
            b.product_name = 'iphone'
    );

你可能感兴趣的:(MySQL)