mysql中常用的函数

字符串函数

select concat('hello','mysql');将两个字符串拼接为一个字符串;

select lower('HELLO');把HELLO转换为小写的hello;

select upper('hello');把hello转换为大写的HELLO;

select lpad('hello',10,'-');在字符串hello左侧拼接上“-”,最终输出为长度为10的字符串“-----hello”;

select rpad('hello',20,'!');在字符串hello右侧拼接上“-”,最终输出为长度为20的字符串“hello---------------”;
select trim('  hello mysql   ');去除掉字符串两端的空格;
select substring('hello mysql',1,5);从字符串第1个字符开始截取长度为5的子串,输出结果为“hello”;

数值函数

select ceil(1.1);向上取整,输出结果为2;

select floor(2.1);向下取整,输出结果为2;

select mod(7,2);7/2,取模运算,输出结果为1;

select rand();生成0-1之间的随机小数;

select round(3.1415926,2);四舍五入,保留两位小数,输出结果为3.14;

-- 随机生成一个6位验证码
select rpad(round(rand()*1000000,0),6,'0');

日期函数

select curdate();查询当前日期,输出格式“xxxx-xx-xx”,年月日格式;

select curtime();查询当前时分秒;

select now();查询当前日期,包含年月日,时分秒;

select year(now());查询当前年份;

select month(now());查询当前月份;

select day(now());查询当前天数;

select date_add(now(),interval 10 day);查询当前日期10天后的日期;

select datediff('2022-3-28','2021-10-23');查询两个日期之间差值;

-- 查询所有员工入职天数,并倒序排序
select name,datediff(curdate(),entrydate) as 'entrydays' from emp order by entrydays desc;

流程控制函数

select if(true,'ok','error'); -- 返回'ok'
select if(false,'ok','error'); -- 返回'error'
select ifnull('hello','default'); -- 返回'hello'
select ifnull('','default'); -- 返回''
select ifnull(null,'default'); -- 返回'default'
-- case when then else end演示
-- 将字段工作城市中的北京和上海替换位一线城市,其他都为二线城市
select
       name,
       (case address when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end) as '工作城市'
from emp;
-- 查询学生成绩,>=85优秀,>=60及格,其它不及格
select
       id,
       name,
       (case when chinese>=85 then '优秀' when chinese>=60 then '及格' else '不及格' end) as '语文' ,
       (case when math>=85 then '优秀' when math>=60 then '及格' else '不及格' end) as '数学' ,
       (case when english>=85 then '优秀' when english>=60 then '及格' else '不及格' end) as '英语'
from score;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值