zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

MySQL数据库基础学习(二十二)

2023-02-19 12:23:46 时间

3.3 日期函数

常见的日期函数如下:

演示如下:

A. curdate:当前日期

 select curdate();

B. curtime:当前时间

select curtime();

C. now:当前日期和时间

select now();

D. YEAR , MONTH , DAY:当前年、月、日

select YEAR(now());
select MONTH(now());
select DAY(now());

E. date_add:增加指定的时间间隔

select date_add(now(), INTERVAL 70 YEAR );

F. datediff:获取两个日期相差的天数

select datediff('2021-10-01', '2021-12-01');

案例:

查询所有员工的入职天数,并根据入职天数倒序排序。

思路:入职天数,就是通过当前日期 - 入职日期,所以需要使用datediff函数来完成。

select name, datediff(curdate(), entrydate) as 'entrydays' from emp order by
entrydays desc;

3.4 流程函数

流程函数也是很常用的一类函数,可以在SQL语句中实现条件筛选,从而提高语句的效率。

演示如下:

A. if

select if(false, 'Ok', 'Error');

B. ifnull

select ifnull('Ok','Default');
select ifnull('','Default');
select ifnull(null,'Default');

C. case when then else end

需求: 查询emp表的员工姓名和工作地址 (北京/上海 ----> 一线城市 , 其他 ----> 二线城市)

select
name,
( case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else
'二线城市' end ) as '工作地址'
from emp;

案例:

create table score(
id int comment 'ID',
name varchar(20) comment '姓名',
math int comment '数学',
english int comment '英语',
chinese int comment '语文'
) comment '学员成绩表';
insert into score(id, name, math, english, chinese) VALUES (1, 'Tom', 67, 88, 95
), (2, 'Rose' , 23, 66, 90),(3, 'Jack', 56, 98, 76);

具体的SQL语句如下:

select
id,
name,
(case when math >= 85 then '优秀' when math >=60 then '及格' else '不及格' end )
'数学',
(case when english >= 85 then '优秀' when english >=60 then '及格' else '不及格'
end ) '英语',
(case when chinese >= 85 then '优秀' when chinese >=60 then '及格' else '不及格'
end ) '语文'
from score;

MySQL的常见函数我们学习完了,那接下来,我们就来分析一下,在前面讲到的两个函数的案例场景,思考一下需要用到什么样的函数来实现?

1). 数据库中,存储的是入职日期,如 2000-01-01,如何快速计算出入职天数呢?-------->

答案: datediff

2). 数据库中,存储的是学生的分数值,如98、75,如何快速判定分数的等级呢?---------->

答案: case ... when ...