MySQL之聚合查询和联合查询 |
您所在的位置:网站首页 › mysql查询一列和查询多列效率不一样吗 › MySQL之聚合查询和联合查询 |
一、聚合查询(行与行之间的计算)
1.常见的聚合函数有: 函数 说明 count 查询到的数据的数量 sum 查询到的数据的总和(针对数值,否则无意义) avg 查询到的数据的平均值(针对数值,否则无意义) max 查询到的数据的最大值(针对数值,否则无意义) min 查询到的数据的最小值(针对数值,否则无意义) Select count(*) from student(统计行数) Select count(1) from student(统计第一列数据的行数,如果有null则不算行数) Select sum(math) from student(数学成绩总分) Select sum(math) from student where math > 60(数学大于60的总分) Select avg(math+chinese+english) from student(统计平均总分) Select max(math) from student(数学最高分) Select min(math) from student where math >60(数学大于60的最低分)
2.group by select 中使用 group by 子句可以对指定列进行分组查询。使用 group by 进行分组查询时,select 指定的字段必须是“分组依据字段”,其他字段若想出现在select 中则必须包含在聚合函数中。 select column1, sum(column2), .. from table group by column1,column3; //示例:查询每个角色的最高工资、最低工资和平均工资 Select role,max(salary),min(salary),avg(salary) from emp group by role;3.having group by 子句进行分组以后,需要对分组结果再进行条件过滤时,不能使用 WHERE 语句,而需要用Having //示例:显示平均工资低于1500的角色和它的平均工资 select role,avg(salary) from emp group by role having avg(salary) s2.score and s1.course_id = 1 and s2.course_id = 2;5.子查询 子查询是指嵌入在其他sql语句中的select语句,也叫嵌套查询。 单行子查询:返回一行记录的子查询 select * from student where classes_id=(select classes_id from student where name=’张三’);多行子查询:返回多行记录的子查询 1.使用(not) in 关键字 使用 in select * from score where course_id in (select id from course where name='语文' or name='英文'); 使用not in select * from score where course_id not in (select id from course where name!='语文' and name!='英文'); 1.使用(not) exists 关键字 使用 exists select * from score sco where exists (select sco.id from course cou where (name='语文' or name='英文') and cou.id = sco.course_id); 使用 not exists select * from score sco where not exists (select sco.id from course cou where (name!='语文' and name!='英文') and cou.id = sco.course_id); 在from子句中使用子查询,把一个子查询当做一个临时表使用。(not)in是放在内存中的,如果查询的数据太大,内存中放不下,此时就需要使用(not)exists。exists本质上就是让数据库执行多个查询操作,并把结果放在磁盘中,因此对于exists来说,执行效率大大低于in,而且可读性也不是很好,这种比较适合处理一些特殊的场景。 6.合并查询 合并查询本质上就是把两个查询结果集合并成一个,但是要求这两个结果集的列一样,才能合并。即: 为了合并多个select的执行结果,可以使用集合操作符 union,union all。使用union和union all时,前后查询的结果集中,字段需要一致。 1.union关键字 用于取得两个结果集的并集。当使用该操作符时,会自动去掉结果集中的重复行。 示例: select * from course where id |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |