Mysql基础之常见函数

吾爱主题 阅读:142 2024-04-02 08:01:44 评论:0

一、常见函数分类

1.1单行函数:

  • 字符函数
  • 字符控制函数(concat、substr、length。。。)
  • 大小写控制函数
  • 数学函数
  • 日期函数
  • 流程控制函数

1.2分组函数:

分组函数功能偏向统计,比如,avg()、count()、max()、min()、sum()

单行函数与分组函数:

(1)分组函数:主要用来进行统计、聚合使用到的函数,分组函数接收多个输入,返回一个输出。

(2)单行函数:上面提到的字符函数、数学函数、日期函数、都属单行函数的范畴,单行函数只对一行进行变换,每行返回一个结果。

二、单行函数

字符函数

concat:字符连接函数

substr:截取字符串,

?
1 2 select substr( '李莫愁爱上了陆展元' ,7)  out_put; // 索引由1开始,陆展元 select substr( '李莫愁爱上了陆展元' ,1,3) out_put;// 李莫愁

instr:返回子串第一次出现的索引,如果找不到返回0

?
1 select instr( '杨不殷六侠悔爱上了殷六侠' , '殷六侠' ) as out_put;// 3

trim:去掉左边与右边的空格元素

?
1 2 select length(trim( '    张翠山    ' )) as out_put; select trim( 'aa' from 'aaaaaaaaa张aaaaaaaaaaaa翠山aaaaaaaaaaaa' as out_put;//中间的a并不能去掉

upper:大写转换字符串

lower:小写转换字符串

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

?
1 select lpad( '殷素素' ,2, '*' ) as out_put;// 数字表示指定的长度

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

replace:替换

三、数学函数

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 四舍五入 select round(-1.55);// -2 select round(1.567,2);// 指定字符精度 1.56   向上取整 select ceil(-1.02);// -1   向下取整 select floor(-9.99);// -10   截断 select truncate (1.69999,1);// 1.6   取余 select mod(-10,3); // -1 select mod(-10,-3);// -1 select mod(10,-3);// 1

四、日期函数

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 返回当前系统日期+时间 select now();// 2021-03-16 09:00:35   返回当前系统日期,不包含时间 select curdate();// 2021-03-16   返回当前时间,不包含日期 select curtime();// 09:00:35   可以获取指定的部分,年、月、日、小时、分钟、秒 select year (now()) 年; select year ( '1998-1-1' ) 年; select month (now()) 月; select monthname(now()) 月;   将字符通过指定的格式转换成日期 select str_to_date( '1998-3-2' , '%y-%c-%d' ) as out_put; // 1998-03-02   将日期转换成字符 select date_format(now(), '%y年%m月%d日' ) as out_put;

五、其他函数

?
1 2 3 select version(); // sql版本 select database ();// 当前数据库 select user ();// root@localhost

六、控制函数

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 if函数 select if(10<5, '大' , '小' ); //小   case 函数的使用1: case 后带参,表示某一种确定的情况   case 要判断的字段或表达式 when 常量1 then 要显示的值1或语句1; when 常量2 then 要显示的值2或语句2;   select salary 原始工资,department_id, case department_id when 30 then salary*1.1 when 40 then salary*1.2 when 50 then salary*1.3 else salary end as 新工资 from employees;   case 函数的使用2: case 后不带参数,表示一种模糊的区间   select salary, case when salary>20000 then 'a' when salary>15000 then 'b' when salary>10000 then 'c' else 'd' end as 工资级别 from employees;

到此这篇关于mysql基础之常见函数的文章就介绍到这了,更多相关mysql常见函数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Wang_Pro/article/details/114867345

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容