函数
#将奖金<500的员工奖金提升100,没有奖金的人comm为null
update emp1 set comm = comm +100 where comm <500;
update emp1 set comm = 100 where comm is null;
#使用ifnull函数,将comm 为null 的置为0
update emp1 set comm = ifnull(comm,0) + 100 where comm is null or comm < 500
update classroom set description = ifnull(description,0) +2 where description is null or description < 3;
#1单行函数(返回值只有一条结果):数学函数,字符串函数,日期函数
数学函数:类似于Math类提供
#有个圆,半径为2 求面积
select PI() *2*2;
#向上取整
select ceil(3.00001); #4
#向下取整
select floor(3.999999); #3
#四舍五入取整取几位默认取整
select ROUND(8.45,1); #8.5
select ROUND(8.45,-1); #10
#取模5%2
select mod(5,2);#1
#随机数0到1之间
select rand();#0到1之间[0,1),有0无1
select floor(rand() *100); #100以内的随机数
#幂运算
select pow(2,3); #8
#随机从emp表中获取2条记录
select * from emp order by rand() limit 2;
select * from classroom order by rand() limit 2;
字符函数
#获取字符串长度
select length('this is a dog');
#获取classroom 表中每个描述的长度
select length(`desc`) from classroom1;
#转为小写
select lower('THIS');
#转为大写
select upper('this');
#截取字符串
select substr('This is zs',1,6); #This i,下标从1开始
#替换字符串
select replace ('This is zs','This','t'); #t is zs
#去掉两端空格,给字段起别名
select trim(' this is zs ') trim; #this is zs
#左填充 select LPAD(str,len,padstr),中间为字符串整体长度如果小于的话,会进行字符串截取
select LPAD('this',1,'is') #左填充 t
select LPAD('this',10,'is') #左填充 isisisthis
# RPAD(str,len,padstr) #右填充
select RPAD('this ',10,' is'); #右填充this is i
日期函数
#获取当前时间
select now() now; 2019-06-18 10:18:14
#获取系统时间
select sysdate() ;2019-06-18 10:18:55
#获取当前日期
select CURRENT_DATE();select CURDATE(); #简写 2019-06-18
select CURRENT_TIME(); 10:20:24
select year('2019-09-09'); #2019
select year(NOW()); #2019
select MONTH(NOW()); #6
select day(NOW()); #18
#获取当前月的最后一天
select last_day('2018-02-02'); #2018-02-28
#判断当前年份是否是闰年,是返回1 不是返回0
select day(last_day(RPAD(year(NOW()),10,'-02-01')))=29 leapYear ;
#日期计算
#计算2天以后是几号
select DATE_ADD(now(),INTERVAL 2 day);#2019-06-20 10:33:15
select DATE_ADD(now(),INTERVAL 2 MONTH);#2019-08-18 10:33:47
#2.聚合函数
#min() ,max(), avg(), count(), sum();
#计算工资最高的人
select max(sal) from emp;
select max(`description`) from classroom;
select AVG(`description`) from classroom;#平均值
select count(*) from classroom; #查询表中有多少记录
select count(1) from classroom; #查询表中有多少记录
select count(description) from classroom; #查询表中description字段的非空个数
select sum(description) from classroom; #对description进行求和
#3分组函数 Group by 分组条件 having 分组之后进行检索
查询公司每个部门的平均奖金
select avg(sal) from emp group by(deptno)
查询学每个班级平均钱数
select cid,avg(money) from student group by(cid);
#查询平均工资大于2000的部门编号和平均工资,
#1.where 不能再Group by之后
#2。where 中不能使用聚合函数
select deptno,avg(sal) from emp group by deptno having avg(sal)>2000;
#查询班级中名字相同的人重复数据
select *from student
where sname in (select sname from student group by sname having count(*) >= 2)
#4加密函数
select md5('root');MD5 加密字符串
select sha('root'); 比MD5复杂
select PASSWORD('root');
MySQL进阶之路七(函数)
猜你喜欢
转载自blog.csdn.net/ZhaiAlan/article/details/92803192
今日推荐
周排行