MySQL查询select常用函数
统计
count计数
count(字段名)
--计算查询结果中该字段的总条目数
count(条件表达式)
--计算查询结果中符合该条件的条目数
sum求和
sum(字段名)
--计算查询结果中该字段的总和
sum(条件表达式)
--计算查询结果中符合该条件的条目数(因为条件表达式结果为true时加数为1,该函数效果与count相同)
注意
- count与sum括号内结果为null时不计数
- count与sum未统计到有效数值时,返回null,此时应使用IFNULL函数处理返回值为0
条件判断
if
if(条件表达式,条件为true时返回值,条件为false时返回值)
多条件表达式
条件1 and 条件2;
条件1 or 条件2;
(条件1 and 条件2) or 条件3;
(条件1 or 条件2) and (条件3 or 条件4);
((条件1 and 条件2) or 条件3) and 条件4;
--可自由发挥
ifnull:转换null为0
ifnull(表达式,0)
--表达式结果为null时返回O
coalesce:转换null为0
coalesce(表达式,0)
--表达式结果为null时返回O
case when 多结果情况判断
case 条件表达式/算式 when 结果1 then 返回值1 when 结果2 then 返回值2;
--可判断多个结果,此处给出两个结果为例
时间处理
时间格式转换
str_to_date(时间参数,目标格式)
常用格式
%Y-%m-%d %H:%i:%s
年 月 日 时 分 秒
时间修改
date_add(时间参数, interval 数值 时间单位)
date_sub(时间参数, interval 数值 时间单位)
时间参数需使用str_to_date格式化
修改一个或多个多个时间单位
数据类型处理
cast参数类型转换
cast(待转换类型字段 as 目标转换类型);
--常用转换类型: char date datetime decimal unsigned time
字符串
substring/substr字符串片段截取
substring(字符串参数,起始位置) --截取到终点
substring(字符串参数,起始位置,截取长度) --截取固定长度
position为负时表示从后往前截取