MYSQL优化之GROUP BY

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值