MySQL常用函数
字符串函数
- concat(s1, s2, …, sn) 拼接多个字符串
- upper(s) 将字符串中所有字符转化为大写字母
- lower(s) 将字符串中所有字符转化为小写字母
- lpad(str, n, pad) 用pad左填充字符串str至长度为n的字符串
- rpad(str, n, pad) 类似lpad,但右填充
- trim(str) 去掉字符串头尾的空格
- length(str) 获取字符串长度
- substring(str, start, len) 返回字符串str从start起len长度的字符串(MySQL中字符串下标从1开始计算)
1 | select concat('Hello', 'World'); -- Hello World |
数值函数
- ceil(x) 向上取整
- floor(x) 向下取整
- mod(x, y) 求 x % y
- rand() 返回一个0到1的浮点数
- round(x, y) 对x进行四舍五进,保留y位小数
1 | select ceil(1.1); -- 2 |
日期函数
- curdate() 返回当前日期(年月日)
- curtime() 返回当前时间(时分秒)
- now() 返回当前日期+时间(YY-MM-DD HH:MM:SS)
- year(date) 解析日期字符串并返回年份
- month(date) 解析日期字符串并返回月份
- day(date) 解析日期字符串并返回天数
- date_add(date, interval expr type) 计算date加上一个日期偏移量的结果
- datediff(date1, date2) 返回date1到date2的日数差
1 | select now(); -- 2024-08-19 15:40:00 |
流程函数
- if(value, t, f), 若value为真,则返回t,否则返回f
- ifnull(value1, value2) , 若value1不为空,则返回value1,否则返回value2
- case when [val1] then [res] … end 条件分支语句
1 | select if(true, '1', '2'); -- 1 |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 多巴胺の小窝!
评论