Mysql:if、case when、any、all、not in使用

if

if(value,value2,value3),如果value结果为true(一般为表达式),返回value2,否则value3

case when

方式1(相当Java的if..else if.. else)

case
when 条件1 then 结果1
when 条件2 then 结果2
else 结果3 end;

一般用在select语句中

方式2(相当Java的switch)

case [表达式]
when 常量值1 then 值1
when 常量值2 then 值2
else 常量值3 end;

[表达式]的结果等于对应常量值时,则then后面的值

any

any多用于where和having,下面举例子说明:

1. 查询其他部门 比 job_id = 'A'的部门任意员工工资低的员工信息

select *
from employees
where job_id != 'A' 
and salry < any(
	select e.salary
	from employees e
	where job_id = 'A'
)

这里的any表示任一的意思,只要salary比子查询中其中一个值低就行。

all

any多用于where和having,下面举例子说明:

1. 查询其他部门 比 job_id = 'A'的部门所有员工工资低的员工信息

select *
from employees
where job_id != 'A' 
and salry < all(
	select e.salary
	from employees e
	where job_id = 'A'
)

这里的all表示全部的意思,salary比子查询中所有值都低(等同于比最小值还小)就行。

not in

还是举例说明:

查询员工job_id不存在于job表的的员工信息

select *
from employees
where job_id not in
(
	select job_id
	from job
)

上述有个问题,子查询中返回job_id会出现null的情况,因此在外层使用not in的查询结果是有问题的。建议大家使用not in时要考虑子查询是否为null的情况,严谨写法是:

select *
from employees
where job_id not in
(
	select job_id
	from job
	where job_id is not null
)
posted @ 2022-09-14 13:34  爱编程DE文兄  阅读(278)  评论(0编辑  收藏  举报