您的位置:首页 > 数据库 > MySQL

MYSQL优化之GROUP BY

2017-10-15 11:56 295 查看

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: