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;

相关推荐
卡西里弗斯奥4 小时前
【达梦数据库】dblink连接[SqlServer/Mysql]报错处理
数据库·mysql·sqlserver·达梦
杨俊杰-YJ5 小时前
MySQL 主从复制原理及其工作过程
数据库·mysql
一个儒雅随和的男子6 小时前
MySQL的聚簇索引与非聚簇索引
数据库·mysql
独泪了无痕7 小时前
MySQL查询优化-distinct
后端·mysql·性能优化
hadage2338 小时前
--- Mysql事务 ---
数据库·mysql
天天向上vir10 小时前
缓存三大问题及其解决方案
java·redis·mysql
初尘屿风10 小时前
vue3项目,旅游景点页面
java·javascript·vue.js·spring boot·后端·mysql·ecmascript
Cikiss11 小时前
图解MySQL【日志】——Buffer Pool
java·数据库·后端·mysql
又逢乱世12 小时前
Node.js 连接 mysql 数据库
数据库·mysql·node.js
君败红颜12 小时前
MySQL 使用 Performance Schema 定位和解决慢 SQL 问题
数据库·sql·mysql