# 字符函数
-- concat 拼接
select concat('hell0,',title) from blog ;
-- length 获取字符长度
select length(title) from blog where id = 1;
-- char_length 获取字符个数
select char_length(title) from blog where id = 1;
-- substr 截取字符串
/**
substr 起始索引为 1
substr(str,起始索引,截取字符长度)
substr(str,起始索引)
*/
select substr(title,1,3) from blog;
select substr(title,2) from blog;
-- instr 获取 第二个参数 第一次出现的索引
select instr('你你你我是帅哥是帅哥','帅哥');
-- trim 去除前后空格
select trim(' 你 好 ');
-- 去除前后指定字符 x
select trim('x' from '我xxx好xx') as a;
-- lpad/rpad 左/右填充 (str,最终字符个数,填充字符)
select lpad('你好',10,'a');
select rpad('你好',10,'a');
-- upper 大写 / lower 小写
select upper('a');
select lower('A');
-- strcmp 比较两个字符大小
select strcmp('adb','aaa');
# 数学函数
-- ABS 绝对值
select ABS(-2.4);
-- CEIL向上取整 返回>= 该参数的最小整数
SELECT CEIL(1.09);
-- floor 向下取整,返回<= 该参数的最大整数
select floor(1.09);
-- round 四舍五入 (数值,保留个数)
select round(1.92343242);
select round(1.92343242,3);
-- truncate截断(小数值,截断位数)
select truncate(1.453543,0);
-- mod 取余
select mod(-10,3);
# 日期函数
-- now 当前时间
select now();
-- curdate 当前日期
select curdate();
-- 日期间隔时间
select datediff('1995-11-06',curdate()) as number;
-- 时间
select date_format('1995-11-06','%Y年%m月%d日 %H小时%i分钟%s秒');
-- 按指定格式解析字符串为日期类型
select str_to_date('5/20 1998','%m/%d %Y');
# 流程控制函数
-- if 函数 类似java 的三元运算符(判断条件,true,false)
select if(100>9,'好','不好');
-- case 函数
/**
情况1 :(从前到后判断 ,满足直接输出)
case 表达式
when 值1 then 结果1
when 值2 then 结果2
....
else 结果n
end
*/
select a.id,a.views,
case
when views>30 then 'A'
when views>20 then 'B'
WHEN views>10 then 'C'
else 'D'
end as number
from blog a;
# 分组函数
/**
说明 : 分组函数往往用于实现将一组数据进行统计计算,最终得到一个值,又称为聚合函数或者统计函数
分组函数清单子:
sum(字段名) :求和
avg(字段名):求平均数
max(字段名):求最大值
min(字段名):求最小值
count(字段名):计算非空字段值的个数
*/
-- 查询emp 表中记录数量
select count(id) from blog;
-- 相当于增加了一个列 值为1 然后计数
select count(1) from blog;
mysql 函数学习
最新推荐文章于 2024-08-14 14:47:29 发布