mysql查询中常见函数
单行函数
-
concat() 拼接字符串
-
length()参数值的字节个数
-
ifnull()
-
upper()大写
-
lower()小写
-
substr()、substrin()截取字符串
select substr(‘abcdefghijk’,1,3); 输出’abc’
select substr(‘abcdefghijk’,3); 从第三个开始输出,即’cdefghijk’
-
instr()
select instr(‘abcdefghijk’,‘bcd’) ;输出结果是2
-
trim()去前后空格
select trim(‘a’ from ‘aaaaaaaabaaaaabaaaaaaa’);执行结果是baaaaab
-
lpad()左填充
select lpad(‘aaa’,5,‘*’);结果是**aaa
-
rpad()右填充
select rpad(‘aaa’,5,‘*’);结果是aaa**
聚合函数
select sum(salary) from employees;
select avg(salary) from employees;
select min(salary) from employees;
select max(salary) from employees;
select count(salary) from employees;
#去重
select count(distinct(salary)) from employees;
# count函数
select count(*) from employees; #统计总行数
select count(1) from employees; #统计总行数,加常量
# 时间差
select datediff(max(hiredate),min(hiredate)) diffrence from employees;
# 差值直接减
select max(salary)-min(salary) difference from employees;
数学函数
# 四舍五入
select round(-1.55); # 1
select round(1.567,2); #1.57
# 向上取整
select ceil(1.00)
# floor 向下取整
select floor(-9.99); #-10
# truncate截断
select truncate(1.6999,1);#1.69
# mod取余
select mod(10,3); #1
日期函数
# now返回当前日期+时间
select now();
# curdate只返回日期
select curdate();
# curtime只返回时间
select curtime();
# 获取指定的部分
select year(now()) 年;
流程控制函数
select if(10<5,'大','小');
# 部门号为30,显示工资为原来的1.1倍
# case跟的department_id是需要考虑的字段
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;
其他函数
select version();
select database();
select user();