SQL - 函数

字符串函数

#contact
select concat('Hello', ' mysql');
#lower
select lower('Hello');
#upper
select upper('Hello');
#lpad 左填充到总长度多少位
select lpad('s',5,'--');
#rpad 右填充到总长度多少位
select rpad('s',5,'--');
#trim 去除两端空格
select trim(' Hello  world  ');
#subString 截取字符串, 下标是从1开始的
select substring('hello',1);

 数值函数

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

-- floor  向下取整, 结果为2
select floor(2.9);

-- mod 取模,结果为2
select mod(2,3);
select mod(5,3);

-- rand随机数,1以内的随机数
select rand();

-- round四舍五入,保留几位小数,结果为3.34
select round(3.335,2);

-- 生成6位的随机数
select lpad(round(rand() * 1000000 ,0), 6 ,'0');

日期函数

 

-- 当前日期
select curdate();
-- 当前时间
select curtime();
-- 当前日期+时间
select now();

-- 获取date年
select year(now());
-- 获取date月
select month(now());
-- 获取date日
select day(now());

-- 指定date + 一个时间间隔
-- 往后推70秒
select date_add(now(), interval 70 second );
-- 往后推70分钟
select date_add(now(), interval 70 minute );
-- 往后推70天
select date_add(now(), interval 70 day);
-- 往后推70月
select date_add(now(), interval 70 month);
-- 往后推70年
select date_add(now(), interval 70 year);

-- 2个date之间相差的天数
-- 第一个参数在第二参数之前,会出现负数,结果为-31
select datediff('2022-01-01','2022-02-01');
-- 第一个参数在第二参数之后,正数,结果为31
select datediff('2022-02-01','2022-01-01');

select name, datediff(curdate(),entrydate) entrydays from emp order by entrydays desc;

 流程函数

 

-- if
select if(true, 'ok', 'error');
select if(false, 'ok', 'error');

-- ifnull
select ifnull('ok', 'default');
-- 为空字符串时,也不是null,依然返回空字符串
select ifnull('', 'default');
select ifnull(null, 'default');


-- case when then else end
-- 需求:查询员工姓名和工作地址(北京/上海 ---> 一线城市, 其他 --->二线城市)
select name,
       (case workaddress
           when '北京' then '一线城市'
           when '上海' then '一线城市'
           else '二线城市' end) as '工作地址'
from emp;

 

select name,
       case when math >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end as mathscore,
       case when english >= 85 then '优秀' when english >= 60 then '及格' else '不及格' end as englishscore,
       case when chinese >= 85 then '优秀' when chinese >= 60 then '及格' else '不及格' end as chinesescore
from score

总结

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值