二、MySql -- 常见函数

156 阅读2分钟

常见函数

概念:将一组逻辑语句封装在方法体中,对外暴露方法名

优点:隐藏了实现细节

提高了代码的重用性

使用:select 函数名() 【from 表】;

特点:方法的名称

函数的功能

常见函数:

  • 1、单行函数

    oncat、length、ifnull等

  • 2、分组函数

    做统计使用,又称为统计函数

单行函数

  1. 字符函数
  2. 数学函数
  3. 日期函数
  4. 其他函数
  5. 流程控制函数

1、字符函数

length 获取参数值的字节个数

select length('str');
select length('张三')  #一个汉字占三个字节

concat 拼接字符串

select concat(str1,str2...)

upper lower

select upper(str);  #字符串大写
select lower(str);  #字符串小写  

substr 截取字符串

select substr('srting',7);  #索引从1开始
select substr('string',1,3);  #第二个值表示要截取的长度,并非索引

instr 显示字符串的其实索引

select instr('string','str');
注:若找不到对应的字符串,返回0

trim 去除字符串前后的‘ ’

select trim('   str    ');

select trim('a' from 'aaaaaaaa张aaaaaa')  #去除对应前后字符串,

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

select lpad('string',10,'*')
注:长度为字符串总长度,长度小于原始字符串长度时,截取原字符串对应长度得字符

replace 替换字符串

select replace('张无忌爱上周芷若','周芷若','赵敏')
输出:张无忌爱上赵敏

2、数学函数

#round  四舍五入
select round(1.65);
输出:2
select round(1.567,2)  #保留小数点后两位
输出: 1.57

#ceil  向上取整,返回>=该参数的最小证书
select ceil(1.002);
输出:2

#floor 向下取整,返回<=该参数的最小证书
select floor();

#truncate 截断
select truncate(1.65,1);  #保留小数点后几位
输出:1.6

#mod 取余  值:a-a/b*b
select mod(10,3);
输出:1
注:被除数为正,则结果为正,反之一样

3、日期函数

#now 返回当前系统日期和时间
select now();

#curdate  返回当前日期
select curdate();

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

#获取指定的部分,年、月、日、小时、分钟、秒
select year(now());
select month(now());
select monthname(now());  #返回英文月份

#str_to_date 将日期格式的字符转化为指定格式的日期

str_to_date('9-13-1999','%m-%d-%Y')
date_format  将日期转化为字符

B6D5D499-9065-4054-A399-02F340B7AF33.png

4、流程控制函数

if 函数

select if10>5,'t','f');

case 函数

使用一

case 要判断的字段或者表达式
when 常亮1 then 要显示的值
when 常亮1 then 要显示的值
...
else 要现实的值或语句
end

使用二

cese 
when 条件1 then 要显示值1或语句1
when 条件2 then 要显示值2或语句2
...
else 要显示值n或语句n
end