SQL 函数

本文最后更新于:2024年3月18日 凌晨

SQL 函数

数据函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ABS(x)            -- 绝对值 abs(-10.9) = 10
FORMAT(x, d) -- 格式化千分位数值 format(1234567.456, 2) = 1,234,567.46
CEIL(x) -- 向上取整 ceil(10.1) = 11
FLOOR(x) -- 向下取整 floor (10.1) = 10
ROUND(x) -- 四舍五入去整。
MOD(m, n) -- m%n m mod n 求余 10%3=1
PI() -- 获得圆周率。
POW(m, n) -- m^n
SQRT(x) -- 算术平方根。
RAND() -- 随机数。
TRUNCATE(x, d) -- 截取d位小数。
SIGN(0); /*符号函数:负数返回-1,正数返回1,0返回0*/
IFNULL(expr1,expr2);/*如果expr1不是NULL,IFNULL()返回expr1,否则它返回expr2*/
IF(expr1,expr2,expr3);/*如果expr1是TRUE(expr1<>0且expr1<>NULL),那么IF()返回expr2,否则它返回expr3*/

字符串函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
LENGTH(string)            -- string长度,字节。
CHAR_LENGTH(string) -- string的字符个数。
SUBSTRING(str, position [,length]) -- 从str的position开始,取length个字符。
REPLACE(str ,search_str ,replace_str) -- 在str中用replace_str替换search_str
INSTR(string ,substring) -- 返回substring首次在string中出现的位置。
CONCAT(string [,...]) -- 连接字串。
CHARSET(str) -- 返回字串字符集。
LCASE(string) -- 转换成小写。
UCASE(string) -- 转换成大写。
LEFT(string, length) -- 从string中的左边起取length个字符。
RIGHT(string, length) -- 从string中的右边起取length个字符。
LOAD_FILE(file_name) -- 从文件读取内容。
LOCATE(substring, string [,start_position]) -- 同instr,但可指定开始位置。
REPEAT(string, count) -- 重复count次。
LPAD(string, length, pad) -- 重复用pad加在string开头,直到字串长度为length
LTRIM(string) -- 去除前端空格。
RPAD(string, length, pad) --在str后用pad补充,直到长度为length
RTRIM(string) -- 去除后端空格。
STRCMP(string1 ,string2) -- 逐字符比较两字串大小。

日期和时间函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
NOW(), CURRENT_TIMESTAMP();     -- 当前日期时间。
CURRENT_DATE(); -- 当前日期。
CURRENT_TIME(); -- 当前时间。
DATE('yyyy-mm-dd hh:ii:ss'); -- 获取日期部分。
TIME('yyyy-mm-dd hh:ii:ss'); -- 获取时间部分。
DATE_FORMAT('yyyy-mm-dd hh:ii:ss', '%d %y %a %d %m %b %j'); -- 格式化时间。
UNIX_TIMESTAMP(); -- 获得unix时间戳。
FROM_UNIXTIME(); -- 从时间戳获得时间。

-- 获取年月日,时分秒。
YEAR(NOW());
MONTH(NOW());
DAY(NOW());
HOUR(NOW());
MINUTE(NOW());
SECOND(NOW());

系统信息函数

1
2
VERSION();  /*版本*/
USER(); /*用户*/

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!