MYSQL优化之GROUP BY
使用group by进行分组的时候,会自动对分组的字段进行排序
mysql> explain select id from ds_goods group by type_id\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: ds_goods
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 3011379
Extra: Using temporary; Using filesort
1 row in set (0.00 sec)
如果不需要这个排序可以使用order by null取消它.
mysql> explain select id from ds_goods group by type_id order by null\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: ds_goods
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 3011379
Extra: Using temporary
1 row in set (0.00 sec)
可以看到在Extra的部分,使用了order by null就不会提示Using filesort了.
Using temporary表明的是用到了临时表.
我们可以通过对这个字段建立索引的方式解决这个问题.
mysql> alter table ds_goods add key type (type_id);
Query OK, 0 rows affected (10.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
需要注意的是当表很大的时候,建立索引是需要时间的.
再次查询.
mysql> explain select id from ds_goods group by type_id order by null\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: ds_goods
type: range
possible_keys: type
key: type
key_len: 4
ref: NULL
rows: 11
Extra: Using index for group-by
1 row in set (0.00 sec)
本文介绍了如何通过取消默认排序及建立索引来优化MySQL中GROUP BY的查询性能。使用ORDER BY NULL可以避免不必要的文件排序,而为分组字段创建索引则能显著提升查询效率。
1261

被折叠的 条评论
为什么被折叠?



