当前位置:   article > 正文

【SQL】1084. 销售分析III (多种解法;is null 和 =null 的区别图示 )

【SQL】1084. 销售分析III (多种解法;is null 和 =null 的区别图示 )

前述

知识点学习:MySQL 中 is null 和 =null 的区别

题目描述

leetcode题目: 1084. 销售分析III

在这里插入图片描述
在这里插入图片描述

写法一

思路:“所有售出日期都在这个时间内”,也就是“在这个时间内售出的商品数量等于总商品数量”

-- 解法1:ACCEPT “所有售出日期都在这个时间内”,也就是“在这个时间内售出的商品数量等于总商品数量”
select A.product_id, B.product_name
from Sales A
left join Product B
on A.product_id = B.product_id
group by A.product_id
having COUNT(sale_date between '2019-01-01' and '2019-03-31' or null) = COUNT(*);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

写法二

思路:最小的日期,最大的日期,都在2019-01-01至2019-03-31之间。

-- 解法2:ACCEPT: 思路:最小的日期,最大的日期,都在2019-01-01至2019-03-31之间。
select A.product_id, B.product_name
from Sales A
left join Product B
on A.product_id = B.product_id
group by A.product_id
having min(A.sale_date) >= '2019-01-01' and max(A.sale_date) <= '2019-03-31';
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

写法三

参看,大佬的题解

select product_id, product_name
from product 
where product_id not in (
  select s.product_id
  from sales s
  where sale_date < '2019-01-01' or sale_date > '2019-03-31'
)
and product_id in (
  select s.product_id
  from sales s 
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

写法四

我最初的思路:如何确定某product_id是否也在除了2019年春季之外的时间也销售?

  • 我的想法:先找:不在2019年春季销售的product_id,再取反(not in)。就是仅在2019年春季销售的product_id。
  • 我的漏洞:有可能存在没卖的产品,所有要连表找到 sale_date is null 的product_id
-- ACCEPT
select product_id, product_name 
from Product 
where product_id not in (
    select distinct Product.product_id
    from Product 
    left join Sales on Product.product_id = Sales.product_id
    where sale_date is null or sale_date not between '2019-01-01' and '2019-03-31' 
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

记录自己的错误点:用法:is null (而不是 = null)(虽然不报错,但是检索不出来)。
null 在MySQL中不代表任何值,通过运算符是得不到任何结果的,因此只能用 is null(默认情况)

is null 和 =null 的区别图示

举例:

select *
from Product 
left join Sales 
on Product.product_id = Sales.product_id
where sale_date is null or sale_date not between '2019-01-01' and '2019-03-31' 
-- 错误点:is null 而不是 = null, 虽然不报错,但是检索不出来。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

在这里插入图片描述
对比

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/263037
推荐阅读
相关标签
  

闽ICP备14008679号