SQL函数:
数据库中的函数与Java中的函数类似,都是完成一定功能的代码的集合。根据函数操作数据行数可将SQL函数分为单行函数和多行函数
- 单行函数:单行函数仅对单条数据中的列进行操作并且返回一个结果;
- 多行函数:多行函数可以操作成组的多条数据,每组返回一个结果,所以多行函数又称之为组函数;
首先创建一个表并添加数据:
create table student(
id char(1) primary key,
name varchar(8),
sex char(2) default '男' ,
age int(3) default 0
)
drop table student
insert into student values ('1','王明','男',18);
insert into student values ('2','孙丽','女',17);
insert into student values ('3','王明','男',27);
insert into student (id,sex,age) values ('4','男',27);
多行函数:
常用的count(); max(); min(); avg();等等
- select count(id) from studen
- select count(name) from studen;聚合函数(多行函数)不统null字段
- select max(age) from student
- select min(age) from student
- select avg(age) from student
单行函数:
字符串函数:
- length(column_name|str):返回字符串存储长度
select length(name) length from student
- char_length(column_name|str):返回字符串中字符个数
select char_length(name) length from student
- concat(str1, str2,......):将多个字符串首尾相连后返回;
select concat(id,name,sex,age) info from student
- concat_ws(separator,str1, str2,......):将多个字符串按照执行separator进行首尾相连;
select concat_ws(',',id,name,sex,age) info from student
- trim( ):返回去掉str源字符串两端、前缀或后缀字符串。由于不怎么使用在实际开发中,所以只例举其中一个。
tselect trim(' Tom ')
- substr(str,pos[,len]):从源字符串str中的指定位置pos开始取len个字符串并返回;
注意:是从pos位置开始取,并且包括pos位置的数,另外len可以不填写,此时就是截取pos及其以后的全部字符串
select substring('hello world',7);
select substring('hello world',7,2) sub
- replace(str, from_str, to_str):将源字符串str中所有子串form_str(大小写敏感替代成字符串to_str并返回替换后的字符串
select replace('prefix.mysql.com','prefix','www') repl
- reverse(str):返回字符串str反转结果
select reverse('12345‘);
数值函数:
- mod(x,y):取x与y的余数;
select mod(1,3)
- round(x[,y]):返回参数x的四舍五入值,该值有y位小数;不指定第二个参数,则默认为0
select round(1.99,0),round(1.58),round(1.28,1);
- truncate(x,y):返回数字x截断后的结果,该值有y位小数;
select truncate(1.55678,0),truncate(1.5678998,1);
日期函数:
- now():获得当前日期+时间
select now()
- date_format(date,format):获取指定格式的日期
select date_format(now(),'%Y%m') date
转换函数:
- convert(value,type):将value转换为type类型,type可以是char(字符型)、date(日期型)、time(时间型)、datetime(日期时间型)、 signed(整型) 和decimal(浮点型)类型中的一个
select convert(now(),char(10))
分组函数:
- group by:用于将表中数据划分为若干个组,group by后面用于指定分组的依据
select sex,count(id) from student group by sex
- having():where后面不能使用多行函数,只能使用单行函数和字段,having关键字弥补了这一不足:having子句用于对分组结果进行约束
select name from student group by name having count(name)>1
其他函数:
- if(expr1,expr2,expr3): expr1为TRUE,返回expr2,否则返回expr3
select if(name is NULL,'未知',name) name from student
- ifnull(expr1,expr2):expr1不是NULL,返回expr1,否则返回expr2。
select ifnull(name,'未知') name from student