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;

相关推荐
这孩子叫逆5 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
掘根7 小时前
【网络】高级IO——poll版本TCP服务器
网络·数据库·sql·网络协议·tcp/ip·mysql·网络安全
Bear on Toilet8 小时前
初写MySQL四张表:(3/4)
数据库·mysql
无妄啊______8 小时前
mysql笔记9(子查询)
数据库·笔记·mysql
Looooking8 小时前
MySQL 中常用函数使用
数据库·mysql
island13149 小时前
从 InnoDB 到 Memory:MySQL 存储引擎的多样性
数据库·学习·mysql
ZZDICT9 小时前
MySQL 子查询
数据库·mysql
柳鲲鹏9 小时前
编译成功!QT/6.7.2/Creator编译Windows64 MySQL驱动(MinGW版)
开发语言·qt·mysql
一个很帅的帅哥10 小时前
实现浏览器的下拉加载功能(类似知乎)
开发语言·javascript·mysql·mongodb·node.js·vue·express
dbln10 小时前
MySQL之表的约束
数据库·mysql