您的位置:首页 > 其它

每天进步一点点——优化GROUP BY、or、和嵌套语句

2015-08-20 17:31 579 查看

优化GROUP BY语句

如果查询包括GROUP BY但用户想要避免排序结果的消耗,则可以指定ORDER BY NULL禁止排序:

mysql>explain select payment_date,sum(amount) from payment group by payment_date\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: payment

        type: ALL

possible_keys: NULL

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 16086

        Extra: Using temporary; Using filesort

1 row in set (0.00 sec)

 

ERROR:

No query specified

 

mysql>explain select payment_date,sum(amount) from payment group by payment_dateorder by null\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: payment

        type: ALL

possible_keys: NULL

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 16086

        Extra: Using temporary

1 row in set (0.00 sec)

由于缺少了filesort,从而降低了消耗时间

 

ERROR:

No query specified

优化嵌套查询

mysql> explain select * from customerwhere customer_id not in (select customer_id from payment)\G;

*************************** 1. row***************************

          id: 1

 select_type: PRIMARY

       table: customer

        type: ALL

possible_keys: NULL

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 599

       Extra: Using where

*************************** 2. row***************************

          id: 2

 select_type: DEPENDENT SUBQUERY

       table: payment

        type: index_subquery

possible_keys: idx_fk_customer_id

         key: idx_fk_customer_id

     key_len: 2

         ref: func

        rows: 13

       Extra: Using index

2 rows in set (0.00 sec)

 

ERROR:

No query specified

 

如果使用join来完成这个查询工作,速度将会快很多。

mysql> explain select * from customer aleft join payment b on a.customer_id=b.customer_id where b.customer_id isnull\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: a

        type: ALL

possible_keys: NULL

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 599

       Extra: NULL

*************************** 2. row***************************

          id: 1

 select_type: SIMPLE

       table: b

        type: ref

possible_keys: idx_fk_customer_id

         key: idx_fk_customer_id

     key_len: 2

         ref: sakila.a.customer_id

        rows: 13

       Extra: Using where; Not exists

2 rows in set (0.00 sec)

 

ERROR:

No query specified

从以上执行计划可以看出查询关联的类型从index_subquery调整为了ref,join之所以更有效率一些,是因为MySQL不需要在内存中创建临时表来完成这个逻辑上需要两个步骤的查询。

优化OR条件

对于含有OR的查询子句,如果利用索引,则OR之间的每个条件都必须有索引,如果没有,要考虑增加索引。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: