文章目录
- 一、日期函数
- 二、字符串函数
-
- (一)案例:
-
- 1.获取emp表的ename列的字符集
- 2.要求显示exam_result表中的信息,显示格式:"XXX的语文是XXX分,数学XXX分,英语XXX分"
- 3.求学生表中学生姓名占用的字节数
- 4.截取EMP表中ename字段的第二个到第三个字符
- [5. 以首字母小写的方式显示所有员工的姓名](#5. 以首字母小写的方式显示所有员工的姓名)
- 三、数学函数
- 四、其它函数
-
- [(一)user() 查询当前用户](#(一)user() 查询当前用户)
- (二)md5(str)对一个字符串进行md5摘要,摘要后得到一个32位字符串
- (三)database()显示当前正在使用的数据库
- (四)password()函数,MySQL数据库使用该函数对用户加密
- [(五)ifnull(val1, val2) 如果val1为null,返回val2,否则返回val1的值](#(五)ifnull(val1, val2) 如果val1为null,返回val2,否则返回val1的值)
一、日期函数
(一)常用日期函数

1.获得年月日:
cpp
select current_date();

2.获得时分秒:
cpp
select current_time();

3.获得时间戳:
cpp
select current_timestamp();

4.在日期的基础上加日期:
cpp
select date_add('2017-10-28', interval 10 day);

5.在日期的基础上减去时间:
cpp
select date_sub('2017-10-1', interval 2 day);

6.计算两个日期之间相差多少天
cpp
select datediff('2017-10-10', '2016-9-1');

(二)案例-1:
- 创建一张表,记录生日
cpp
create table tmp(
id int primary key auto_increment,
birthday date
);

(三)案例-2:
- 创建一个留言表
cpp
mysql> create table msg (
id int primary key auto_increment,
content varchar(30) not null,
sendtime datetime
);
- 插入数据
- 显示所有留言信息,发布日期只显示日期,不用显示时间
cpp
select content,date(sendtime) from msg;

- 请查询在2分钟内发布的帖子
cpp
select * from msg where date_add(sendtime, interval 2 minute) > now()
二、字符串函数

(一)案例:
1.获取emp表的ename列的字符集
cpp
select charset(ename) from EMP;
2.要求显示exam_result表中的信息,显示格式:"XXX的语文是XXX分,数学XXX分,英语XXX分"
cpp
select concat(name, '的语文是',chinese,'分,数学是',math,'分') as '分数' from
student;
3.求学生表中学生姓名占用的字节数
cpp
select length(name), name from student;
注意:length函数返回字符串长度,以字节为单位。如果是多字节字符则计算多个字节数;如果是单字节字符则算作一个字节。比如:字母,数字算作一个字节,中文表示多个字节数(与字符集编码有关)
- 将EMP表中所有名字中有S的替换成'上海'
cpp
select replace(ename, 'S', '上海') ,ename from EMP;
4.截取EMP表中ename字段的第二个到第三个字符
cpp
select substring(ename, 2, 2), ename from EMP;
5. 以首字母小写的方式显示所有员工的姓名
cpp
select concat(lcase(substring(ename, 1, 1)),substring(ename,2)) from EMP;
三、数学函数
(一)案例

1.绝对值
cpp
select abs(-100.2);

2.向上取整
cpp
select ceiling(23.04);

3.向下取整
cpp
select floor(23.7);

4.保留2位小数位数(小数四舍五入)
cpp
select format(12.3456, 2);

5.产生随机数
cpp
select rand();

四、其它函数
(一)user() 查询当前用户
cpp
select user();

(二)md5(str)对一个字符串进行md5摘要,摘要后得到一个32位字符串
cpp
select md5('admin')

(三)database()显示当前正在使用的数据库
cpp
select database();

(四)password()函数,MySQL数据库使用该函数对用户加密
cpp
select password('root');

(五)ifnull(val1, val2) 如果val1为null,返回val2,否则返回val1的值
cpp
select ifnull('abc', '123');

cpp
select ifnull(null, '123');
