mysql常用函数

1.数学函数
#向上取整
select ceil(3.14),ceil(-3.14)
4 -3
#向下取整
select floor(3.14),floor(-3.14)
3 -4

#四舍五入
select round(3.14),round(3.54)

#截断(注意需要指定小数位数)
select  truncate(3.14,0),truncate(3.99,0)
#随机数  0-1之间的随机数
select rand()

#生成1-10之间的随机数  [1,10)
select floor(rand()*10)

select POW(5,3) as 5的三次方
select SQRT(16) 16的平方根(负数开方结果null)

2.字符串函数
#替换
select REPLACE(‘hello’,‘l’,‘w’)
#字符串截取 SUBSTRING(字符串,开始下标,截取的长度) 下标从1开始
select SUBSTRING(‘hello,world’ ,1,2)
#反转
select reverse(‘hello,world’)
#字符串(字节)长度 一个汉字占3个字节
select length(‘中国人’) #6
#字符长度(一个汉字占2个字节)
select CHAR_LENGTH(‘中国’)#2

#大小写转换
select UPPER('hello') ,UCASE('hello')
select Lower('Hello') ,LCASE('HeLLO')

#填充
Lpad(字符串,长度,填充符)   左填充
Rpad(字符串,长度,填充符)   右填充

删除
Ltrim()左删除
Rtrim()右删除
trim()左右删除

3.日期函数

#当期日期
select curdate(),current_date()
#当期日期和时间
select now()
#当前时间
select curtime()
#世界时间和日期(不包括时区)
select UTC_TIME()
select utc_date()

#日期增加
select date_add('2020-1-7', interval 15 day)
select date_add('2020-1-7', interval 15 month)

#日期减少
select date_sub('2020-1-7', interval 15 day)
select date_sub('2020-1-7', interval 15 year)

#时间差值
select datediff('2020-1-7','2020-1-24')
select timediff('17:00',CURTIME())

#显示星期  
select DAYOFWEEK(curdate())-1 as 星期
select DAYOFMONTH(curdate()) as 日
select MONTH(curdate())  as 月份
select year(curdate()) as 年

4.流程控制
case语句
(1) case 值 when 值1 then 结果1
when 值2 then 结果2

when 值n then 结果n
else 其他结果
end
#类似switch(v) case 值1:

(2)  case  when 条件1  then  结果1
           when 条件2  then  结果2
			  ....
		   when 条件n  then  结果n
		  else  其他结果
      end
	  
--查询工作,无工作显示无业游民
	
	select case job  
			  when '' then '无业游民'
			  when '初级软件工程师'  then '程序员'
			  when  'SALESMAN'   then '销售'
			  else  job
		   end
	from emp


	select case when job='' then '无业游民'
				when job='初级软件工程师' then '程序员'
				when job='SALESMAN' then '销售'
				else job
			END
	from emp

--1000-1500 低工资  1500-3000 中等工资   3000以上显示 高工资
	select ename ,sal, (case when sal<1500 and sal>=1000 then '低工资'
							when sal<3000 and sal>=1500 then '中等工资'
							when sal>=3000 then '高工资'
							else '无此标准'
					   end)  as 工资等级
	from emp

(3)if语句
if(条件,成立结果1,不成立结果2)

(4) ifnull语句
ifnull(不为空结果1,为空的结果2)

-comm奖金判断,为空显示‘无奖金’	
select ename,comm,ifnull(comm,'无奖金')
from emp

select ename,comm, if(comm is null ,'无奖金',comm)
from emp

你可能感兴趣的:(mysql)