题目描述

(通过次数20,179 | 提交次数23,397,通过率86.25%)

销售表Sales:
+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| year        | int   |
| quantity    | int   |
| price       | int   |
+-------------+-------+
(sale_id, year) 是销售表 Sales 的主键.
product_id 是关联到产品表 Product 的外键.
注意: price 表示每单位价格
产品表Product:
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
+--------------+---------+
product_id是表的主键.

写一条SQL查询语句获取 Sales表中所有产品对应的 产品名称 product_name 以及该产品的所有 售卖年份 year和 价格 price 。
查询结果中的顺序无特定要求。
查询结果格式示例如下:
Sales 表:
+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+ 
| 1       | 100        | 2008 | 10       | 5000  |
| 2       | 100        | 2009 | 12       | 5000  |
| 7       | 200        | 2011 | 15       | 9000  |
+---------+------------+------+----------+-------+
Product 表:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100        | Nokia        |
| 200        | Apple        |
| 300        | Samsung      |
+------------+--------------+
Result 表:
+--------------+-------+-------+
| product_name | year  | price |
+--------------+-------+-------+
| Nokia        | 2008  | 5000  |
| Nokia        | 2009  | 5000  |
| Apple        | 2011  | 9000  |
+--------------+-------+-------+

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/product-sales-analysis-i
//测试数据
Create table If Not Exists Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table If Not Exists Product (product_id int, product_name varchar(10));

insert into Sales (sale_id, product_id, year, quantity, price) values ('1', '100', '2008', '10', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('2', '100', '2009', '12', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('7', '200', '2011', '15', '9000');

insert into Product (product_id, product_name) values ('100', 'Nokia');
insert into Product (product_id, product_name) values ('200', 'Apple');
insert into Product (product_id, product_name) values ('300', 'Samsung');

解题思路

Sales表保存了产品的所有销售数据。对于产品,仅保存了产品ID。

Product表保存了所有产品的基本信息。包括产品ID、产品名称等。

题目要求:查询出每个产品的销售年份、销售价格。产品以产品名称的方式显示。

很明显,要查询的信息中,产品名称在Product表中,销售年份以及价格在Sales表中。如果需要一起查询出来,那么就需要将两张表关联起来。

因为题目要求只展示出Sales表中有销售信息的产品,所以,可以使用Sales表作为主表关联Product表。

至于使用左关联还是内关联,因为Product表保存了所有的产品信息,也就是说,Sales表中的所有产品都在Product表中,所以使用左关联或内关联都是可以的。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    b.product_name,
    a.year,
    a.price
from Sales a
inner join Product b
on a.product_id = b.product_id;
picture loss