【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(*);

写法二

思路:最小的日期,最大的日期,都在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';

写法三

参看,大佬的题解

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 
)

写法四

我最初的思路:如何确定某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' 
);

记录自己的错误点:用法: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. SQL--IFNULL()、NULLIF()、ISNULL()函数 简单明了讲解

    2024-03-15 13:20:03       49 阅读
  2. Oracle中Null‘‘区别

    2024-03-15 13:20:03       66 阅读
  3. js nullundefined区别

    2024-03-15 13:20:03       42 阅读
  4. mysql null空值区别

    2024-03-15 13:20:03       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 13:20:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 13:20:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 13:20:03       87 阅读
  4. Python语言-面向对象

    2024-03-15 13:20:03       96 阅读

热门阅读

  1. iOS runtime理解和应用场景

    2024-03-15 13:20:03       41 阅读
  2. python 读取pdf 将每页转成jpg

    2024-03-15 13:20:03       46 阅读
  3. C#使用Entity Framework Core处理数据库(一)

    2024-03-15 13:20:03       42 阅读
  4. 【趣味学算法】07_爱因斯坦的数学题

    2024-03-15 13:20:03       40 阅读
  5. C++ 纯虚函数定义语法,及作用

    2024-03-15 13:20:03       44 阅读
  6. 【设计模式】常见设计模式

    2024-03-15 13:20:03       35 阅读
  7. 【笔记】学习Android.mk(三)

    2024-03-15 13:20:03       39 阅读
  8. js手写实现 Promise.all

    2024-03-15 13:20:03       47 阅读