SQL函数

字符串函数

-- 字符串拼接
select concat('Hello','MySQL');

-- 转小写
select lower('Hello');

-- 转大写
select upper('Hello');

-- 左填充 用- 对 ‘01’ 左边进行填充 达到5个字符串长度
select lpad('01',5,'-');

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

-- 去除左右的空格
select trim('  Hello   MySQL  ');

-- 索引从1开始
select substring('Hello MySQL',1,5);

-- 由于需求变更 , 企业员工的工号, 统一为5位数, 目前不足5位数的全部在前面补0
update emp set workno = lpad(workno,5,'0');

数值函数

-- 向上取整
select ceil(1.5);

-- 向下取整
select floor(1.6);

-- 求模
select mod(7,4);

-- 随机数0-1
select rand();

-- 四舍五入 第二个参数是保留的小数位
select round(2.345,2);

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

日期函数

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

-- 当前时间
select curtime();

-- 当前日期加时间
select now();

-- 年 月 日
select YEAR(now());

select MONTH(now());

select DAY(now());

-- 返回一个日期/时间值加上一个时间间隔后的时间值
select date_add(now() , INTERVAL 70 DAY );

-- 两个指定时间相差天数
select datediff('2021-12-01' , '2021-10-01');

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

流程函数

-- if value为true 返回第一个
select if(true, 'OK' , 'ERROR');

-- value不为空 返回第一个
select ifnull('OK','Default');
select ifnull('null','Default');

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



--
create table score(
    id int comment 'ID',
    name varchar(20) comment '姓名',
    math int comment '数学',
    english int comment '英语',
    chinese int comment '语文'
) comment '学员成绩表';
insert into score(id, name, math, english, chinese) values (1,'lmz',66,77,88) , (2,'lkh',44,33,55);

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 chinese >= 85 then '优秀' when chinese >= 60 then '及格' else '不及格' end) '语文'
from score;

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值