MySQL常用函数总结
MySQL函数包括数学函数、字符串函数、日期和时间函数、条件判断函数、系统信息函数、加密函数、格式化函数等
1. 数学函数
ABS(x)
PI()
SQRT(x)
MOD(x,y)
CEIL(x)、CEILING(x)
FLOOR(x)
ROUND(x)、ROUND(x,y)
SIGN(x)
POW(x,y)和、POWER(x,y)
EXP(x)
LOG(x)
LOG10(x)
RADIANS(x)
DEGREES(x)
SIN(x)、ASIN(x)
COS(x)、ACOS(x)
TAN(x)、ATAN(x)
COT(x)
二、聚合函数(常用于GROUP BY从句的SELECT查询中)
AVG(col)
COUNT(col)
MIN(col)
MAX(col)
SUM(col)
GROUP_CONCAT(col)
三、字符串函数
ASCII(char)
BIT_LENGTH(str)
CONCAT(s1,s2...,sn)将s1,s2...,sn
CONCAT_WS(sep,s1,s2...,sn)将s1,s2...,sn
INSERT(str,x,y,instr)
FIND_IN_SET(str,list)
LCASE(str)或LOWER(str)
LEFT(str,x)
LENGTH(s)
LTRIM(str)
POSITION(substr,str)
QUOTE(str)
REPEAT(str,srchstr,rplcstr)
REVERSE(str)
RIGHT(str,x)
RTRIM(str)
STRCMP(s1,s2)
TRIM(str)
UCASE(str)或UPPER(str)
四、日期和时间函数
CURDATE()或CURRENT_DATE()
CURTIME()或CURRENT_TIME()
DATE_ADD(date,INTERVAL int keyword)
SELECTDATE_ADD(CURRENT_DATE,INTERVAL 6 MONTH);
DATE_FORMAT(date,fmt)
DATE_SUB(date,INTERVAL int keyword)
SELECTDATE_SUB(CURRENT_DATE,INTERVAL 6 MONTH);
DAYOFWEEK(date)
DAYOFMONTH(date)
DAYOFYEAR(date)
DAYNAME(date)
SELECT DAYNAME(CURRENT_DATE)
FROM_UNIXTIME(ts,fmt)
HOUR(time)
MINUTE(time)
MONTH(date)
MONTHNAME(date)
SELECT MONTHNAME(CURRENT_DATE);
NOW()
QUARTER(date)
SELECT QUARTER(CURRENT_DATE)
WEEK(date)
YEAR(date)
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP());
SELECT EXTRACT(YEAR_MONTH FROM CURRENT_DATE);
SELECT EXTRACT(DAY_SECOND FROM CURRENT_DATE);
SELECT EXTRACT(HOUR_MINUTE FROM CURRENT_DATE);
SELECT PERIOD_DIFF(200302,199802);
SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)),'%Y')+0 AS age
FROM employee;
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birthday, '%Y') -(DATE_FORMAT(NOW(),
'00-%m-%d') <DATE_FORMAT(birthday, '00-%m-%d')) AS age from employee
五、加密函数
AES_ENCRYPT(str,key)
AES_DECRYPT(str,key)
DECODE(str,key)
ENCRYPT(str,salt)
ENCODE(str,key)
MD5()
PASSWORD(str)
SHA()
示例:
SELECT ENCRYPT('root','salt');
SELECT ENCODE('xufeng','key');
SELECT DECODE(ENCODE('xufeng','key'),'key');
SELECT AES_ENCRYPT('root','key');
SELECT AES_DECRYPT(AES_ENCRYPT('root','key'),'key');
SELECT MD5('123456');
SELECT SHA('123456');
六、格式化函数
DATE_FORMAT(date,fmt)
FORMAT(x,y)
INET_ATON(ip)
INET_NTOA(num)
TIME_FORMAT(time,fmt)
SELECT FORMAT(34234.34323432,3);
SELECT DATE_FORMAT(NOW(),'%W,%D %M %Y %r');
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d');
SELECT DATE_FORMAT(19990330,'%Y-%m-%d');
SELECT DATE_FORMAT(NOW(),'%h:%i %p');
SELECT INET_ATON('10.122.89.47');
SELECT INET_NTOA(175790383);
七、类型转化函数
BINARY,CHAR,DATE,TIME,DATETIME,SIGNED,UNSIGNED
SELECT CAST(NOW() AS SIGNED INTEGER),CURDATE()+0;
SELECT 'f'=BINARY 'F','f'=CAST('F' AS BINARY
);
|