MySQL常见的函数

MySQL常见的函数

1. 常见的字符函数
-- concat:拼接字符串
select concat(first_name,'_',last_name)
from employees;

-- length:获取字符串的字节长度
select length('你好,各位,hello');

-- upper:小写转换成大写
select upper('john');

-- lower:大写转换成小写
select lower('HELLO');

-- char_length:获取字符串长度
select char_length('hello,世界');

-- substr:截取字符串
-- sql 语言中的索引都是从1开始
select substr('hello,world!',7);

-- instr:获取字符串中子串第一次出现的索引
select instr('hello,world!','wo');

-- trim:去除字符串中前后的无效字符,默认无效字符为空格
select trim('   hello,world!  ');
select trim('a' from 'aaahello,world!aaa');

-- lpad:用指定的字符左填充字符串到指定的长度
select lpad('hello',10,'*');

-- rpad:用指定的字符右填充字段串到指定的长度
select rpad('hello',10,'*');

-- replace:用指定字符或者字符串替换字符串中的内容
select replace('hello,world','hello','world');
2. 常见的数学函数
-- 数学函数
-- round:四舍五入
select round(1.65);
select round(1.577,2);

-- ceil:向上取整,返回大于或等于该参数的最大整数
select ceil(1.00);

-- floor:向下取整,返回小于或等于该参数的最大整数
select floor(9.09);

-- truncate:截断参数数据,不进行四舍五入
select truncate(1.488,2);

-- mod:取余函数,结果为a-a/b*b
select mod(10,3);
3. 常见的日期函数
-- 日期函数
-- now:返回当前系统日期和时间
select now();

-- curdate:返回当前系统的日期,不包含时间
select curdate();

-- curtime:返回当前系统的时间,不包含日期
select curtime();

-- 获取日期的指定部分:年/月/日/小时/分钟/秒
select year(now()) 年, month(now()) 月, day(now()) 日, hour(now()) 时, minute(now()) 分, second(now()) 秒;
select monthname(now());

-- str_to_date:将日期格式的字符转换成指定格式的日期
select str_to_date('2020-10-01','%Y-%m-%d');

-- date_format:将日期转换为字符
select date_format('2020-10-01','%Y年%c月%d日');

-- datediff:两个日期之间相隔的天数
select datediff(now(), '1998-08-02');
4. 其他函数
-- version:查询 MySQL 的版本
select version();

-- database:查询目前正在使用的数据库
select database();

-- user:查询目前登录的用户
select user();
5. 流程控制函数
-- 流程控制函数
-- if函数:if-else的效果
select if(10>5,'大','小');

-- case函数:①类似于Java中的switch case的效果;②类似于多重if
/*
case 要判断的字段或者表达式
	when 常量1 then 值1或者语句1;
	when 常量2 then 值1或者语句2;
	...
	else 默认值或者默认的语句;
end
*/
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 新工资
from employees;

/*
case 
	when 条件1 then 值1或者语句1;
	when 条件2 then 值2或者语句2;
	...
	else 默认的值或者默认的语句;
end
*/
select salary 原始工资,
	case
		when salary>20000 then 'A'
		when salary>15000 then 'B'
		when salary>10000 then 'C'
		else 'D'
	end 工资级别
from employees;
6. 分组函数
-- 分组函数:用作统计使用,又称为聚合函数或者统计函数
-- 分类:sum(求和函数),avg(平均值函数),max(最大值),min(最小值),count(计算个数)
select sum(salary),avg(salary),max(salary),min(salary),count(salary) from employees;

-- 参数支持的类型
-- sum/avg:支持数值类型
-- max/min/count:支持任何类型

-- sum/avg/max/min/count:忽略NULL值进行计算

-- 分组函数和distinct配合使用可以对数据去重
select sum(distinct salary), sum(salary) from employees;
select count(distinct salary), count(salary) from employees;

-- count函数
-- 对于MYISAM引擎:count(*)效率较高
-- 对于INNDB引擎,count(*)和count(1)的效率差不多,但是比count(字段)效率高

-- 和分组函数一同查询的字段只能是group by后的字段
posted @ 2020-12-06 21:55  Yanko24  阅读(29)  评论(0)    收藏  举报