MySQL入门篇——(五)查询数据之单表查询(内置函数)

什么是内置函数 也即mysql数据库定义好的函数
1.单行函数
划分依据:单行函数仅对单条数据中的列进行操作并且返回一个结果;

select length(name) from student    #获取字符串字符个数

2.多行函数 对多行数据进行统计的函数
多行函数可以操作成组的多条数据,每组返回一个结果,所以多行函数又称之为组函数;

select count(id) from student
#count 统计有多少条数据
#max 统计最大值
#min
#avg 平均值
 
 /*删除之前创建的student表*/   
drop table student  
 /*建立新表*/ 
create table student(
 id char(1) primary key,
 name varchar(8),
 sex char(2) default '男' ,
 age int(3) default 0
)
     
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);
    
#字符串函数
#length()		#因为使用UTF-8编码,一个汉字三个字节,一个字母一个字节,所以‘王明’  这种长度是6
select length(name) from student
#char_length():  字符有多少个,注意与length的区别
select char_length(name) from student

#concat() 拼接   使多列变成一列
select concat(id,',',name)个人信息 from student
select concat(id,',',name,',',age)个人信息 from student
#concat_ws  先指定连接符,后面说明连接内容,在使用相同连接符拼接的内容较多时较为简化,连接符只用输一次
select concat_ws(',',id,name,age) 个人信息 from student

#trim      /*去左右空格*/
select trim(name) from student
#reverse   /*反转*/
select reverse(name) from student 

#replace  替换 
/*replace(str, from_str, to_str):将源字符串str中所有子串form_str
(大小写敏感替代成字符串to_str并返回替换后的字符串;*/
select replace(name,'_','#') from student
select from dual

#substr截取  截取下标从一开始
select substr('abcdef',2,2)from dual
select name from student

#strcmp 
/*strcmp(expr1,expr2):两个字符串相同则返回0;第一个小于第二个返回-1,否则返回1;*/
select*from student
select strcmp(name,'孙丽')from student

select mod(1,3) from dual
/*mod(x,y):取x与y的余数;*/

#返回参数x的四舍五入值,该值有y位小数;不指定第二个参数,则默认为0;
select round(1.58,0),round(1.58),round(1.298,1);
/*	结果		2	 		2			 1.3			*/
#truncate(x,y):返回数字x截断后的结果,该值有y位小数;
select truncate(1.58,0),truncate(1.298,1);
#	结果 			1				1.2

select now();   #当前时间

#date_format(date,format):获取指定格式的日期替换下面'%Y-%m-%d-%H-%i-%s'中的-为想要的符号
select date_format(now(),'%Y-%m-%d-%H-%i-%s');

#datediff(date1,date2):返回(date1-date2)天;
select datediff(now(),'2019-12-31')

#convert 转换  
/*convert(value,type):将value转换为type类型,type可以是char(字符型)、date(日期型)、time(时间型)、datetime(日期时间型)、 signed(整型) 和decimal(浮点型)类型中的一个*/
select convert(now(),char(10));  #10表示前十位,包含连接符   
select now();   #当前时间 2019-05-10 16:21:17
select convert(now(),date);  #转日期型  2019-05-10
select convert(now(),time);  #转时间型  16:22:39
select convert(now(),datetime); #转日期时间型 2019-05-10 16:23:07
select convert('99',signed)+1;  #99转整型并进行+1运算
select convert('99.99',decimal(5,2))+0.01;  #浮点型

#其他函数   类似三目运算
#if(expr1,expr2,expr3): expr1为TRUE,返回expr2,否则返回expr3
	 select if(name is NULL,'未知',name) from student;   
	 /*name is NULL成立,返回未知,不成立,返回原name*/
#ifnull(expr1,expr2):expr1不是NULL,返回expr1,否则返回expr2。
	select ifnull(name,'未知') from student;   #如果name是null,则返回未知,不是null,返回原内容

猜你喜欢

转载自blog.csdn.net/qq_44724446/article/details/90057036