1. 字符函数
1. length
// 获取参数值的字节个数
select length('join');
2. concat
// 拼接字符串
select concat(last_name,'_',first_name) from employees;
3. upper、lower
// 大小写转换
select upper('john');
// 将姓变大写,名变小写,然后拼接
select concat(upper(last_name),lower(first_name));
4. substr
// 字符串,下标
select substr('李莫愁爱上了路展元',7);
select substr('李莫愁爱上了路展元',1,3);
mysql中索引从1开始,(但是limit是从0开始)
5. trim
// 修剪前后空格
select trim(' 张翠山 ');
6. replace
// 替换字串
select replace('张无忌爱上了周芷若','周芷若','赵敏');
2. 数学函数
1. round
// 四舍五入,小数点后四舍五入
select round(1.65);
// 四舍五入,保留小数点后两位
select round(1.576,2)
2. ceil、floor
// ceil,向上取整
select ceil(1.003);
// floor,向下取整
select floor(9.9);
3. truncate
// 小数点后几位截断
select truncate(1.6999,2);
3. 日期函数
1. now
// 返回当前日期和时间(精确到秒)
select now();
// 2021-08-26 23:49:34
2. curdate
// 返回当前日期,不含时间
select curdate();
3. curtime
// 返回当前时间,不含日期
select curtime();
4. year、month、day
// 获取年份
select year(now());
select year('2021-08-26');
// 获取月份
select month(now());
5. str_to_date
// 将字符串按照指定格式解析成日期
select str_to_date('9-13-1999','%m-%d-%Y');
//1999-09-13
select str_to_date('9-13-1999 14:22:21','%m-%d-%Y %H:%i:%s');
//1999-09-13 14:22:21
// %Y 四位的年份 %H 24小时制 %i 分钟
6. date_format
// 将日期转换成指定格式字符串输出
select date_format(now(),'%Y年%m月%d日');
7. date_add
// 在日期上按指定单位进行加减
select date_add(now(),interval -1 day);
8. to_days
// 将指定日期转换为0000年开始到指定日期的天数
select to_days(now());
4. 其他函数
1. version、database、user
select user();
2. group_concat
- 将分组后的按某个字段进行拼接操作。默认使用逗号分割。
select uid, group_concat(score) from user group by uid;
- 可以指定分隔符
select uid, group_concat(score separator ':') from user group by uid;
- 也可以将拼接字段指定排序规则
select uid, group_concat(score order by price separator ':') from user group by uid;
5. 高级函数
1. if
// 类似java三元运算符
select name,if(sex==1,'男','女') as sex from employees;
2. ifnull
// 判断字段是否为null, 为空返回0,不为空返回bonus值
select name, ifnull(bonus,0) as '奖金' from employees;
3. isnull
顾名思义,判断字段是否为空
6. 正则表达式的使用
select * from emp where name regexp '^T';
select * from emp where name regexp '2$';
select * from emp where name regexp '[uvw]';
符号 | 含义 |
^ | 在字符串开始处进行匹配 |
$ | 在字符串末尾处进行匹配 |
. | 匹配任意单个字符, 包括换行符 |
[abc] | 匹配出现abc中任意一个的字符 |
a* | 匹配零个或者多个a(包括空串) |
a+ | 匹配一个或者多个a(不包括空串) |
a? | 匹配零个或者一个a |
a1|a2 | 匹配a1或a2 |
a(m) | 匹配m个a |
a(m,) | 至少匹配m个a |
a(m,n) | 匹配m个a 到 n个a |
a(,n) | 匹配0到n个a |