本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句
摘要:本文主要介绍SQL的常见函数中的单行函数
常见函数
概念:类似于java中的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处:1、隐藏了实现的细节 2、提高了代码的重用性
调用:select 函数名(实参列表)【from 表】;
特点:1、函数名(叫什么)
2、函数功能(干什么)
分类:
1、单行函数 如 concat、length、 ifnull
2、分组函数 做统计使用,又称为统计函数、聚合函数、组函数
单行函数
又细分为字符函数、数学函数、日期函数、其它函数【补充】、流程控制函数【补充】
1、字符函数(参数为字符)
select length('john'); 输出4
select length('发送happy'); 输出8 与mysql默认字符集有关,一个汉字占两个长度
#length函数比较特殊,mysql中只有它是按的字节长度,其它函数基本都按字符。
select concat(last_name, '_', first_name) 姓名 from employees;
select upper('john');
select lower('JOHN');
select concat(upper(last_name), lower(first_name)) 姓名 from employees;
substr、substring
select substr('李莫愁爱上了陆展元', 6) out_put; #索引从6开始! 输出:了陆展元
select substr('李莫愁爱上了陆展元', 1,3) out_put; #包括1和3位置上的字符 输出:李莫愁
select instr('杨不悔爱上了殷六侠','殷六侠') as out_put; #返回后边的字符串第一次在前边的字符串中出现的索引。
select length(trim(' 张翠山 ')) as out_put;
select trim('a' from 'aaa行aaa好aaa') as out_put; #把a当做空格
select lpad('殷素素', 10, '*') as out_put; #用指定字符进行右填充
select replace('张无忌爱上了周芷若', '周芷若', '赵敏') as out_put;
2、数学函数(参数为数值)
select round(-1.55); #输出-2
select round(-1.555, 2); #输出 -1.56
select ceil(1.02); #向上取整
select floor(1.02); #向下取整
select truncate(1.69999, 2); #小数点后截取2位
select mod(-10, 3); #等价于-10%3 结果的符号等与第一个数的符号
select rand(); #获取随机数,返回0-1之间的小数
3、日期函数(参数为类型)
select now(); #输出:2019-12-10 19:06:48
select curdate(); #输出:2019-12-10
select curtime(); #输出:19:06:48
select year(now()) 年;
select year(hiredate) 年 from employees;
select month(now()) 月;
select monthname(now()) 月; #输出:December
select str_to_date:将日期格式的字符串转换成指定格式的日期
str_to_date('9-13-1999', '%m-%d-%Y');
select str_to_date('1998-3-2', '%Y-%c-%d') as out_put;
#查询入职日期为1992-4-3的员工信息
select * from employees where hiredate = '1992-4-3';
select * from employees where hiredate = str_to_date('4-3 1992', '%c-%d %Y');
date_format:将日期转换成字符串
select date_format(now(), '%Y年%m月%d日') as out_put;
#查询有奖金的员工名和入职日期(xx月/xx日 xx年)
select last_name, date_format(hiredate, '%m月/%d日 %y年') 入职日期 from employees;
#计算现在的日期和一个给定日期的差值(天数)
select datediff(now(), '2016-6-9');
4、其它函数
select version();
select database(); #输出:root@localhost
select user();
select md5(); #输出1bceb9ca798ffaa9151ac58e38595308
5、流程控制函数
select if(10>5, 'big', 'small'); #java三目运算符
select last_name, commission_pct, if(commission_pct is null, '没奖金,呵呵', '有奖金,嘻嘻') 备注 from employees;
select salary 原始工资, department_id,
case department_id
when 30 then salary*1.1
when 40 then salary*1.2
when 50 then salary*1.3
else salary
end as 新工资
from employees; #case 语句要在case与end之间 语法类似于java的switch case
select salary,
case
when salary>20000 then 'A'
when salary>15000 then 'B'
when salary>10000 then 'C'
else 'D'
end as 工资级别
from employees;
总结:
1、字符函数:
length
concat
substr
instr
trim
upper
lower
lpad
rpad
replace
2、数学函数
round
ceil
floor
truncate
mod
rand
3、日期函数
now
curdate
curtime
year
month
monthname
day
hour
minute
second
str_to_date
date_format
datediff
4、其它函数
version
database
user
md5
5、流程控制函数
if
case