0
点赞
收藏
分享

微信扫一扫

MySQL常用的几种函数你知道嘛?

快乐小码农 2022-04-18 阅读 83
mysql

字符串函数

功能 :

代码演示: 

-- concat(s1,s2,..sn) 字符串拼接
select concat('hello','mysql');

-- lower(str) 字符串全部转为小写
select lower('HELLO');

-- upper(str) 字符串全部转为大写
select upper('hello');

-- lpad(str,n,pad) 左填充 ---01
select lpad('01',5,'-');

-- rpad(str,n,pad) 右填充  01---
select rpad('01',5,'-');

-- trim(str) 去掉字符串头部和尾部的空格
select  trim(' hello mysql ');

-- substring(str,start,len) 字符串截取 这里下标是从1开始的
select substring('hello mysql',1,5);

-- 1.由于业务需求变更,企业员工的工号,统一为5位数,目前不足5位数的全部在前面补0,比如,1号员工的工号应该为00001。
update emp1 set workon = lpad(workon,5,'0');

数值函数

代码演示: 

-- 数值函数
-- ceil (x)  向上取整  -- 2
select ceil(1.1);

-- floor (x) 向下取整 -- 2
select floor(2.9);

-- mod 取模
select mod(6,4);

-- rand 放回0~1的随机数
select rand();

-- round(x,y)  求参数x 的四舍五入的值 保留y位小数
select round(2.345,2);

-- 案例: 通过数据库函数,生成一个六位数的随机验证码
select lpad(round(rand()*1000000,0),6,0) ;

select lpad( round( rand()*1000000 , 0 ),6 ,'0');

日期函数

代码演示: 

-- 日期函数
-- curdate 返回当前日期
select curdate();

-- curtime 返回当前时间
select curtime();

-- now() 返回当前日期和时间
select  now();

-- year month day
select year(now());

select month(now());

select day(now());

-- date_add (date,interval expr type) 往后推迟 70 个月
select date_add(now(),interval 70 month );

-- datediff(date1,date2) 相差天数
select  datediff('2022-4-18','2001-12-2');

-- 查询所有员工的入职天数,并根据入职天数倒叙排序
select name,datediff(curdate(),entrydate) as 'entrydates'from emp1 order by entrydates desc ;

 流程函数

代码演示: 

-- 流程函数
-- if(value,t,f) 如果value 为真,则返回t,否则返回f
select  if(true,'OK','error');

-- ifnull(value1,value2) 如果value1不为空,返回value1,否则返回value2
select ifnull('ok','Default');

select ifnull(' ','Default');

select ifnull(null,'Default');

-- 案例: 统计班级各个学员的成绩,展示的规则如下:
-- >=85 , 展示优秀
-- >=60 , 展示及格
-- 否则, 展示不及格

create table score(
    id int comment 'ID',
    name varchar(20) comment '姓名',
    math int comment '数学',
    english int comment '英语',
    language int comment '语文'
)comment '学员成绩表';

insert into score(id, name, math, english, language) VALUES
(1,'张三',67,88,95),(2,'李四',23,66,90),(3,'王五',56,98,76);

select
       id,
       name,
       (case when math>=85 then '优秀' when math>=60 then '及格' else '不及格' end) '数学',
        (case when english>=85 then '优秀' when english>=60 then '及格' else '不及格' end) '英语',
        (case when language>=85 then '优秀' when language>=60 then '及格' else '不及格' end) '语文'
from score;

 总结:

   

    总结图片来自黑马程序员,如有侵权,立马删除!制作文章不易,如果本篇文章对你有所帮助,可以点赞收藏加关注哦,你们的关注是对小编最大的支持!!!

                            

举报

相关推荐

0 条评论