一,单行处理函数
常用的数据处理函数如下表所示:
lower | 转大写 |
upper | 转小写 |
substr | 取子串(substr{被截取的子串,起始下标(从1开始),被截长度}) |
length | 取长度 |
trim | 去空格 |
str_to_date | 字符串(varchar)转日期(date) |
date_fromat | 日期格式化.。将date类型转换为一定格式的varchar类型。 |
format | 设置千分位。使用:format(数字,'$999.999'); |
round | 四舍五入。round(数字,保留到哪位)。0是保留到整数位,保留几位小数就写几,保留到几位整数就写负几。 |
rand() | 生成0到1的随机数。要生成一百以内的随机数:select round(rand()*100,0) as in100 from user; |
ifnull |
将null转成一个具体值。如果不处理NULL,它与任何数据运算结果都是NULL。用法ifnull(数据,被当作哪个值) |
Notations:
(1)concat(,)用于字符拼接。示例将首字母大写输出:
select concat(upper(substr(userCode,1,1)),substr(userCode,2,length(userCode)-1)) from user;
(2)如果写select 1000 as num from user; 会生成一个字段为num,字面值都是1000,行数跟user相同的列输出
(3)case...when...then...when...then...else...end;使用例如给两种商品涨价:
select productName,productCount as oldPrice,(case productDesc when '饮料-国酒' then productCount*1.2 when '食品-进口食用油' then productCount*1.3 else productCount end) as newPrice from bill;
(4)if语句的使用:if(条件,1,0)表示满足条件则使用数据,不满足则不用
单行处理函数(数据处理函数)的特点:一个输入对应一个输出,而多行处理函数就是多个输入对应一个输出。
二,分组函数(多行处理函数):
特点:输入多行,输出一行。
count | 计数 |
sum | 求和 |
avg | 求平均 |
max | 求最大值 |
min | 求最小值 |
Notations:
(1)分组函数使用必须先进行分组。如果没有风,整张表默认为一份。(2)分组函数自动处理null。但如果使用如Count(*),是会计算null的,而Count(具体字段)不会计入null。(3)分组函数不能直接使用在where子句中,因为where执行顺序在分组函数之前,它执行的时候还没分组。(4)所有分组函数可以组合起来一起用
三,分组查询
一些需求需要分组:select...from...group by...order by...;
执行顺序:1,from;2,where;3,group by;4,having;5,select;6,order by;
// 先指定那张表查,再用where筛选有价值的数据,然后进行分组,分组后继续用having筛选,再用select把数据拿出来,最后进行排序
分组举例:
(1)select productDesc,sum(productCount) from bill group by productDesc;
(2) 联合分组:select depto,job,max(sal) from emp group by depto,job;
// 先按照depto分组,再按job分组,最后找出不同depto的不同job的max(sal)
(3)使用having可以对被group by 分组后的数据进一步进行选择性过滤,having只能和group by 联用,不能替代where。如:
select productDesc,max(productCount) from bill group by productDesc having max(productCount)>1000;
Notations:上面的语句执行效率比较低,开发中优先选用where。可以先选择出大于1000的productCount,再按照productDesc分组,然后找到每个productDesc中productCount的最大值,如:
select productDesc,max(productCount) from bill where productCount>1000 group by productDesc;
如果有分组函数,那么select后面只能跟分组过后的字段,因为显示其他没分组的字段无意义或报错。