group by 一般 和集合函数一起使用,使用情况最多的 是count(), 即将 数据按照一定条件分组,再统计每一组的总数, 显然这是非常消耗资源的一种做法. mysql 36军规里 表示尽量少使用 count(),也是这个原因. 如果想对多种条件进行 统计 ,可以使用 判断语句 如sum(if) sum(cses when then) 得到.
虽然希望较少的使用 groupby 但是在必须使用group by 也是需要 优化,减轻服务器压力的
将groupby 的字段 设置为 索引可以有效降低sql 陈本,但是如果 字段在未设置 索引的情况下,想要加快sql执行,可以使用如下:
groupby默认将 分组的字段进行一次排序
select id,name from table_test group by name ;
实际等于
select id,name from table_test group by name order by name ;
在很多情况下 order by name 消耗时间非常多,甚至大于 group by name本身.
如果只需要对数据分组,并没有对分组后的数据排序的需求,使用如下
select id,name from table_test group by name order by null ;
可以大幅降低筛选时间
当然 如果使用的 其他的排序 ,则默认的排序不起作用
select id,name from table_test group by name order by class;