1. mysql时间函数
- curtime()是时间函数,
- curdate()是日期函数,
- now()是包含这俩个所有的时间
mysql> select now(),curtime(),curdate();
+---------------------+-----------+------------+
| now() | curtime() | curdate() |
+---------------------+-----------+------------+
| 2020-07-22 03:22:53 | 03:22:53 | 2020-07-22 |
+---------------------+-----------+------------+
1 row in set (0.00 sec)
2. 单行函数
2.1 字符函数
(1)length
作用: 获取字节量,收到字符集影响。
案例: select length('abc'); select length('刘敏瑞');
show variables like '%char%'; select length('😀');
判断表种某列的字节,帮助我们确认数据类型,判断索引是否需要前缀。
select length(name) as len from world.city order by len desc ;
desc world.city;
(2)concat
作用: 拼接字符串
案例:
mysql> select concat(" mysqldump -uroot -p123 ",table_schema, -> " ",table_name," >/bak/",table_schema,"_",table_name,".sql") as sqltext from -> information_schema.tables where table_schema='world';
mysqldump -uroot -p123 world city >/bak/world_city.sql mysqldump -uroot -p123 world country >/bak/world_country.sql
mysqldump -uroot -p123 world countrylanguage >/bak/world_countrylanguage.sql
(3)upper&lower
作用:转换大小写
案例:
select upper('abc')
select lower('CDE') 1234
(4)substr
作用: 截取字符串
语法: substr(字符串,pos,len)
案例:
select SUBSTR('小龙女被尹志平**了',5,3);
select SUBSTR('小龙女被尹志平**了',1,3);
select substr('李莫愁爱上了陆展元',1,3) as test;
select substr('李莫愁爱上了陆展元',7) as test;
select substr('李莫愁爱上了陆展元',4,3) as test;
(5)instr
作用:返回子集首次次出现的索引。
案例:
select INSTR('杨不悔爱上了殷六侠','殷六侠') AS test;
实际需求:判断某个字符串是否在表中某行出现过。
select id, instr(name,'qingdao') as a from world.city where countrycode='CHN' having a>0 ;
select sum(instr(name,'qingdao')) as a from world.city where countrycode='CHN';
(6)trim
作用: 掐头去尾。
案例:
select TRIM(' 张翠山 ') AS test;
select TRIM('a' from 'aaaaa张翠山aaaa') AS test;
(7)lpad
作用: 左填充
案例:
select LPAD('张柏芝',10,'*') AS test;
(8)rpad
作用:右填充
案例:
select RPAD('张柏芝',10,'*') AS test;
(9)replace
作用:替换
案例:
select REPLACE('谢霆锋***张柏芝','张柏芝','王菲') as test;
例子: 替换-为空
select replace(uuid(),'-','') as uuid;
2.2 数学函数
(1)round
作用: 四舍五入
案例:
select ROUND(3.1415);
select ROUND(3.1415,3);
(2)ceil
作用:向上取 >= 最小整
案例:
select CEIL(3.14);
select CEIL(3.00);
select CEIL(-3.14);
(3)floor
作用:向下<= 最大取整
案例:
select floor(9.99) ;
select FLOOR(9.00);
(4)truncate
作用: 小数点保留截断
案例:
select TRUNCATE(-3.15,1);
(5)mod
作用: 取模
算法:
方法一:
mod(a,b) ---> a-a/b*b
方法二:
被除数为正为正,被除数为负为负
案例:
select MOD(10,3) ;
select MOD(10,-3) ;
select MOD(-10,3) ;
select MOD(-10,-3);
(6)rand
select floor(rand()*10)+1;
作用: 生成某个范围内的随机整数
需求:从以下生成的字符串中,随机截取连续6个字符。
select replace(uuid(),'-','') as uuid; select substr(replace(uuid(),'-','') ,1+floor(rand()*28),10) as ps
(7)