SQL中案例实例01—ifnull(),isnull(),nullif()的使用方法

一、查询应该返回 null —如果不存在,查询应该返回 null

题目描述:获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null
在这里插入图片描述
在这里插入图片描述

1.1 iFnull()的使用

IFNULL(expr1,expr2)的用法:

假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1;
否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。

mysql> SELECT IFNULL(1,0);
-> 1
mysql> SELECT IFNULL(NULL,10);
-> 10
mysql> SELECT IFNULL(1/0,10);
-> 10
mysql> SELECT
IFNULL(1/0,‘yes’);

-> ‘yes’

IFNULL(expr1,expr2)的默认结果值为两个表达式中更加“通用”的一个,顺序为STRING、 REAL或INTEGER。假设一个基于表达式的表的情况或MySQL必须在内存储器中储存一个临时表中IFNULL()的返回值:
CREATE TABLE tmp SELECT IFNULL(1,‘test’) AS test;
在这个例子中,测试列的类型为 CHAR(4)。

1.2 完整代码

select ifNull( 
    (select distinct
a.salary as SecondHighestSalary
from (select
id
,salary
,dense_rank() over(order by salary desc) as rn
from Employee
) a  where a.rn=2)

,null) as SecondHighestSalary

二、返回NUll的对象—找出所有从不订购任何东西的客户

题目描述:某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户

在这里插入图片描述

1.1 isnull()的使用

isnull(expr) 的用法:
如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。
mysql> select isnull(1+1);
-> 0
mysql> select isnull(1/0);
-> 1
使用= 的null 值对比通常是错误的。

isnull() 函数同 is null比较操作符具有一些相同的特性。请参见有关is null 的说明

1.2 完整代码

select 
name
from customers 
left join orders
on customers.id = orders.customerId 
where isnull(customerId);

使用where not in

select name from customers where id not in (
	select customerId from orders
);

三、参考链接

3.2 NULL()的使用

NULLIF(expr1,expr2) 的用法:
如果expr1
= expr2 成立,那么返回值为NULL,否则返回值为 expr1。这和CASE WHEN expr1 = expr2
THEN NULL ELSE expr1 END相同。
mysql> SELECT
NULLIF(1,1);

-> NULL
mysql> SELECT NULLIF(1,2);
-> 1
如果参数不相等,则 MySQL 两次求得的值为 expr1

sql中ifnull(),isnull(),nullif()的使用方法
https://blog.csdn.net/qq_39889961/article/details/85872342

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值