sql入门4--函数

字符串函数

-----字符串函数-----

concat(s1,s2,....)拼接

select concat('Hello ','Mysql');

#str转换为小写

select lower('HELLO');

str转换为大写

select upper('mysql');

向左侧添加 str 位数 要添加的元素

select lpad('1', 3 ,'-');

向右侧添加 str 位数 要添加的元素

select rpad('2', 3 ,'0');

去除首尾空格

select trim(' 1-1 ');

字符串截取------字符串 起始下标(1起始) 截取几个

select substring('你好啊',2,1);

数值函数

cell--向上取整

select ceil(1.2);

foor--向下取整

select floor(1.2);

mod 取余

select mod(1,2);

rand (0-1之间的随机数)

select rand();

#round ---数四舍五入 保留小数

select round(2.345,2);

随机生成5为位数,验证码

select lpad(round(rand()* 100000,0),5,'0');

日期函数

curdate()--当前日期

select curdate();

curtime()

select curtime();

now()--当前年月日时分秒

select now();

year()--年

select year(now());

month()--月

select month(now());

day()--日

select day(now());

date_add----指定时间到 间隔时间后的 时间

指定时间或当前时间 固定语法interval 60 单为(天-月-年)---当前时间60天后的年月日时分秒

select date_add(now() ,interval 60 day );

datediff 得到两个时间之差

select datediff('2021-12-01','2021-10-01');

获取所有员工入职天数,后降序排序----(别名不用 ' ' 括起来 ---否则降序失效 ,别名带空格特殊字符或保留字则需要 ' ' 引起来)

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

SELECT name, DATEDIFF(CURDATE(), entrydate) AS 入职天数 FROM usertable ORDER BY 入职天数 desc ;

SELECT name, DATEDIFF(CURDATE(), entrydate) AS zz FROM usertable ORDER BY zz desc ;

流程控制函数-实现条件筛选-提高语句执行效率

if(value , t , f) 如果value为true 则返回t 否则返回f

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

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

ifNull(value1 , value2) 如果value1不为空 返回value1 否则返回value2

select ifnull(null,'default');

select ifnull('ok','default');

case when then else end

select name,case worknoaddress when '武汉' then '二线' when '北京' then '一线' else '金庸小说' end as 城市 from usertable;

统计班级学生的成绩

>= 85 优秀 >=60 及格 否则不及格

create table score (

id int comment 'ID',

name varchar(50) comment '姓名',

english int comment '英语',

math int comment '数学',

chinese int comment '语文'

) comment '学员成绩表';

insert into score(id,name,english,math,chinese) values (1,'TOM',67,88,98),(2,'ROSE',23,66,90),(3,'Jack',56,98,76);

select name ,

(case when english >= 85 then '优秀' when english >= 60 then '及格' else '不及格' end) as 英语,

(case when math >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end ) as 数学 ,

( case when chinese >= 85 then '优秀' when chinese >= 60 then '及格' else '不及格' end) as 语文

from score;

相关推荐
奇点 ♡1 小时前
MySQL基础题
数据库·sql·mysql
cherry52301 小时前
Java大厂面试真题:Spring Boot + 微服务 + 缓存架构三轮技术拷问实录
jvm·spring boot·mysql·微服务·java面试·分布式架构·redis缓存
唐古乌梁海1 小时前
【mysql】MySQL 数据库迁移
数据库·mysql·adb
JanelSirry1 小时前
真实场景:防止缓存穿透 —— 使用 Redisson 布隆过滤器
数据库·mysql·缓存·redisson·布隆过滤器
mmm.c1 小时前
mysql启动提示1067:进程意外终止
数据库·mysql
一叶飘零_sweeeet2 小时前
MySQL 锁详解
mysql·innodb
沐伊~2 小时前
mysql 安装
数据库·mysql
成为你的宁宁2 小时前
Ubuntu安装mysql5.7及常见错误问题
linux·mysql·ubuntu
努力学习的小廉3 小时前
初识MYSQL —— 复合查询
android·数据库·mysql
熙客15 小时前
Kubernetes是如何保证有状态应用数据安全和快速恢复的
mysql·云原生·容器·kubernetes