LeetCode 1068. 产品销售分析 I

销售表 Sales:

±------------±------+
| Column Name | Type |
±------------±------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
±------------±------+
(sale_id, year) 是销售表 Sales 的主键(具有唯一值的列的组合)。
product_id 是关联到产品表 Product 的外键(reference 列)。
该表的每一行显示 product_id 在某一年的销售情况。
注意: price 表示每单位价格。
产品表 Product:

±-------------±--------+
| Column Name | Type |
±-------------±--------+
| product_id | int |
| product_name | varchar |
±-------------±--------+
product_id 是表的主键(具有唯一值的列)。
该表的每一行表示每种产品的产品名称。

编写解决方案,以获取 Sales 表中所有 sale_id 对应的 product_name 以及该产品的所有 year 和 price 。

返回结果表 无顺序要求 。

结果格式示例如下。

示例 1:

输入:
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 |
±-----------±-------------+
输出:
±-------------±------±------+
| product_name | year | price |
±-------------±------±------+
| Nokia | 2008 | 5000 |
| Nokia | 2009 | 5000 |
| Apple | 2011 | 9000 |
±-------------±------±------+

由于Product表中一行记录的是product_id在某一年的销售情况,因此product_id和year这一组合在Product表中只会出现一次,因此直接用inner join或left join即可:

# Write your MySQL query statement below
select p.product_name, s.year, s.price 
from Sales s, Product p
where s.product_id = p.product_id;

以上代码是隐式inner join。

# Write your MySQL query statement below
select p.product_name, s.year, s.price 
from Sales s inner join Product p
on s.product_id = p.product_id;

以上代码是显式inner join。

# Write your MySQL query statement below
select p.product_name, s.year, s.price 
from Sales s join Product p
on s.product_id = p.product_id;

以上代码使用的是join,与inner join含义相同

# Write your MySQL query statement below
select p.product_name, s.year, s.price 
from Sales s left join Product p
on s.product_id = p.product_id;

以上代码使用的是left join。

介绍一下各种连接:
1.内连接(inner join):两张表都有的数据才会返回,join关键字相当于inner join关键字,如果不用join,直接用where也是隐式的内连接。

2.左连接(left join):左边表中有的数据会返回,不管右边表是否有对应数据,如果右边表没有对应数据,则右边表相关的字段值为null。关键字是left join或left outer join。

3.右连接(right join):右边表中有的数据会返回,不管左边表是否有对应数据,如果左边表没有对应数据,则左边表相关的字段值为null。关键字是right join或right outer join。

4.全连接(full join):返回左右表里的所有记录,如果左(右)边表没有对应数据,则左(右)边表相关的字段值为null。关键字是left join或full join或full outer join。mysql中不支持full join,可以把左连接的结果和右连接的结果UNION一下(不能使用UNION ALL,因为UNION ALL不会去重)。

  • 16
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值