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