MySQL基础之常用函数

数学函数的使用

常用数学函数

函数 作用 函数 作用
ceil() 进一取整 abs() 取绝对值
floor() 舍掉小数部分 power() 幂运算
round() 四舍五入 pi() 圆周率
truncate() 截取小数点后几位 rand()或者rand(x) 0~1之间的随机数
mod 取余数 sign(x) 得到数字符号
exp() 计算e的x次方

用法

select ceil(1.2);
select floor(2.9);
select round(3.56789,2);
select truncate(3.456789,3);
select 10 mod 3;
select id,username,ceil(salary) from user;

字符串常用函数

--char_length():得到字符串的字符数
select char_length('abc');

--length():得到字符串的长度(一个中文字符在utf8下占3个长度)
select length('abc');

--concat(s1,s2,...):将字符串合并成一个字符串(参数里有null最终结果为null)
select concat('a','b','c');

--concat_ws():以指定分隔符拼接字符串
select concat_ws('-','a','b','c',null); --null不起作用
select concat_ws(null,'a','b','c'); --以null作为分隔符结果为null

--upper()|ucase()|lower()|lcase():将字符串转换成大写或者小写
select upper('hello world'),ucase('hello world'),lower('HELLO WORLD'),lcase('HELLO WORLD');

--reverse():字符串的反转
select reverse('abc');

--left()|right():返回字符串的前几个字符或者后几个字符
select left('hello',2),right('hello',2);

--lpad()|rpad():用字符串填充到指定长度
select lpad('abc',10,'?'); --从'abc'左端用'?'填充到10位

--trim()|ltrim()|rtrim():去掉字符串两端的空格
select concat('*',trim(' abc '),'*');

--repeat():重复指定的次数
select repeat('hello',3);

--replace():替换指定的字符串
select replace('hello king','king','queen'); --将'king'替换成'queen'

--substring():截取字符串
select substring('abcdef',1,3); --从1开始截取3位,abc

--strcmp():比较字符串
select strcmp('a','b');

日期时间常用函数的使用

--返回当前日期
select curdate(),current_date();

--返回当前时间
select curtime(),current_time();

--返回当前的日期时间
select now(),current_timestamp(),sysdate();

--返回日期中的月份和月份的名称
select month('2017-02-19');
select month(current_date()),monthname(curdate());

--返回星期几
select dayname(now());

--返回一周内的第几天(1:星期天,2:星期一,...)
select dayofweek(now());

--返回一年中的第几个星期
select week(now());

--返回日期中的年份、月份、天、小时、分钟
select year(now()),month(now()),day(now()),hour(now()),minute(now()),second(now());

--计算两个日期相差的天数
select datediff('2017-03-05','2017-03-01');

其他常用函数

--得到MySQL版本、当前服务器的连接数
select version(),connection_id();

--得到当前的数据库名
select database(),schema();

--得到当前登陆的用户
select user(),current_user(),system_user(),session_user();

--得到上一步插入操作产生auto_increment的值
select last_insert_id();

--加密
select md5('king');

--密码加密算法
select password('root');
posted @ 2019-09-09 15:44  星海|universe  阅读(350)  评论(0编辑  收藏  举报