一、SQL语法——9-数据库函数

9-数据库函数

1.函数可以出现在SQL语句中的任何位置,比较常见的是在select之后和where子句中。

2.根据函数对多行数据的处理方式,函数被分为多行函数和单行函数,单行函数对每行输入值单独计算,每行得到一个计算结果返回给用户;多行函数对多行输入值整体计算,最后只会得到一个结果。

3.多行函数也被称为聚集函数、分组函数,主要完成一些统计功能,在大部分的数据库中基本相同。

4.单行函数在不同数据库中差距较大,MySQL中的单行函数具有如下特征:

(1)单行函数的参数可以是变量、常量或者数据列。单行函数可以接受多个参数,但只返回一个值;

(2)单行函数会对每行单独起作用,每行(可能包含多个参数)返回一个结果;

(3)使用单行函数可以改变数据类型。单行函数支持嵌套使用,即内层函数的返回值可以当做外层函数的参数。

5.单行函数示例:

--创建表并添加记录
create table teacher_table(
    teacher_id int auto_increment,
    teacher_name varchar(255),
    primary key(teacher_id)
);
create table student_table(
    student_id int auto_increment primary key,
    student_name varchar(255),
    java_teacher int,
    foreign key (java_teacher) references teacher_table(teacher_id)
);


insert into teacher_table
values
(null,'teacher_1'),
(null,'teacher_2'),
(null,'teacher_3');

insert into student_table
values
(null,'studnet_1',1),
(null,'studnet_2',1),
(null,'studnet_3',1),
(null,'studnet_4',2),
(null,'studnet_5',2),
(null,null,2),
(null,'studnet_6',null);



--选出teacher_table表中teacher_name列的字符长度
select char_length(teacher_name) from teacher_table;

--计算teacher_name列的字符长度的sin值
select sin(char_length(teacher_name)) from teacher_table;

--计算1.57的sin值,约等于1
select sin(1.57);

--为指定日期添加一定的时间
--interval是关键字,需要一个数值,还需要一个单位
select date_add('1992-03-08',interval 2 month);

--也可使用adddate来增加日期,只能为天增加
select adddate('1992-03-08',3);

--获取当前日期
select curdate();

--获取当前时间
select curtime();

--MD5加密函数
select md5('md5test');




/*
MySQL提供了如下几个处理null的函数
如果student_name列为null,则返回没有名字
*/
select ifnull(student_name,'没有名字')
from student_table;

--如果student_name列的值等于"student_2",则返回null
select nullif(student_name,'student_2')
from student_table;

--如果student_name列的值null则返回"没有名字",如果不为null则返回"有名字"
select if(isnull(student_name),'没有名字','有名字')
from student_table;



--case函数的使用方法(一)
/*
语法格式为:
case value
when compare_value1 then result1
when compare_value2 then result2
...
else result1
end
*/

--如果java_teacher为1则返回“java老师”,如果java_teacher为2则返回“Ruby老师”,否则返回“其他老师”
select student_name,
case java_teacher
when 1 then 'java老师'
when 2 then 'Ruby老师'
else '其他老师'
end
from studnet_table;


--case函数的使用方法(二)
/*
语法格式为:
case
when condition1 then result1
when condition2 then result2
...
else result
end
*/

--id小于3的为初级班,3-6的为中级班,其他的为高级班
select student_name,
case
when student_id<=3 then '初级班'
when student_id<=6 then '中级班'
else '高级班'
end
from student_table;

 

 

 

posted @ 2017-08-03 15:58  丶theDawn  阅读(334)  评论(0编辑  收藏  举报