mysql 4、常见函数

进阶4:常见函数

分类

1、单行函数

如concat、length、ifnull等。

2、分组函数

统计函数、聚合函数、组函数。

功能:用做统计使用,又称为聚合函数或统计函数或组函数。

分类:

sum求和、avg平均值、max最大值、min最小值、count计算个数

特点:

sum、avg 一般用于处理数值行

max、min、count 可以处理任何类型

都忽略null值

count(*)一般用做统计行数

 

单行函数

一、字符函数

#length  获取长度  utf-8中文 1个对3个长度

select length('aaa');

#concat 拼接字符串

select concat(code,'-',id);

#upper、lower 转换大小写

select upper('aaa');

#substr、substring

索引从1开始

#截取从指定索引处后面所有字符

select substr('xxx123456',3) newname;

#截取从指定索引处指定字符长度的字符

select substr('xxx123456',3,3) newname;

#instr 返回字符串的第一次起始索引

select instr('abc123','abc');

#trim 去掉前后空格

select trim('   aaa    ') as new_name;

#lpad 用指定的字符实现左填充指定长度

select lpad(' xxx',2,'*') as new_name;

#rpad 用指定的字符实现右填充指定长度

select rpad(' xxx',2,'*') as new_name;

#replace 替换

select replace('aaaa123','a','b')as new_name;

 

数学函数

#round 四舍五入

select round(1.65)

select round(1.567,2)//保留2位

#ceil 向上取整,返回》=该参数的最小整数

select ceil(1.52);//2

#floor 向下取整,返回《=该参数的最小整数

 select floor(9.99);//9

#truncate 截断

select truncate(1.699999,1);//1.6

#mod取余

select mod(10,3);//余1

selse 10%3;

 

日期函数

#now 返回当前系统日期+时间

select now();

#curdate 返回当前系统日期,不包含时间

select curdate();

#curtime 返回当前时间,不包含日期

select curtime();

#year month day 可以获取指定的部分的年月日小时分钟秒

select year(now());

select month(now());

select day(now());

#str_to_date 将字符转化为日期

select str_to_date('1998-03-02','%Y-%m-%d') as new_name;

#date_format  将日期转换成字符

select date_format(now(),'%Y年%m月%日') as new_name;

 

其他函数

select version();//版本号

select database();//查看当前数据库

select user();//当前用户

 

流程控制函数

#if 函数

select if(10>5,'大','小')

#case 函数

方式一

select code case when 30 then 30*10 when 40 then 40*10 when 50 then 50*10 else code end;

方式二

case when 条件1 then 要显示的值1或语句1 when 条件2 then 要显示的值2或语句2 else 要显示的值或语句 end;

select code case when code>30 then 'a' when code >40 then 'b' code >50 then 'c' else code end;

 

分组函数

功能:用做统计使用,又称为聚合函数或统计函数或组函数。

分类:

sum求和、avg平均值、max最大值、min最小值、count计算个数

特点:

sum、avg 一般用于处理数值行

max、min、count 可以处理任何类型

都忽略null值

count(*)一般用做统计行数

 

使用

select sum(code) from user;

select avg(code) from user;

select max(code) from user;

select min(code) from user;

select count(code) from user;

 

和distinct搭配 去重

select count(distinct code);

 

#count函数详细介绍

select count(*) from user;//统计行数

count(*) 效率最高

 

posted @ 2021-12-30 11:01  熊大大001(前端开发)  阅读(39)  评论(0)    收藏  举报