GROUP BY语法可以根据给定数据列的每个成员对查询结果进行分组统计,最终得到一个分组汇总表。
注意: group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by后面。
正确:
select name, sum(num) from t_project group by name
错误:
select name, max(num),id from t_project group by name
因为:id未出现在group by中, 所以id是随机返回一个,并不是返回max(num)对应一行的id
如果想使用group by也想返回符合条件的行数的其他列,可以使用子查询或者联合查询
联合查询:
select * from t_coverage_task_info a ,(select max(id) id from t_coverage_task_info where projectName='tongzhen_scf_zhuquePlatform' and ip is not null and fId like '4.0.42.%' group by fid) b where a.id=b.id
子查询:
select * from t_coverage_task_info where id in (select max(id) id from t_coverage_task_info where projectName='*****' and fId like '4.0.42.%' group by fid )
但两者的效率不一样, 需要具体对待.如上两个查询,在一个有100w+的数据查询时间差别很多
联合查询: 0.04s
子查询: 3.18s
差别一下就显示出来了。 下面详细看一下每个查询的索引索引使用情况
子查询
explain select * from t_coverage_task_info where id in (select max(id) id from t_coverage_task_info where projectName='*****' and fId like '4.0.42.%' group by fid )

联合查询

子查询使用 in 未使用到索引,联合查询使用到了主键索引。