每天进步一点点——优化GROUP BY、or、和嵌套语句
2015-08-20 17:31
585 查看
优化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之间的每个条件都必须有索引,如果没有,要考虑增加索引。相关文章推荐
- 虚拟化--061 vsphere webclient sdk - SSL certificate verification failed.
- 【Android】时光轴效果
- Some projects cannot be imported because they already exist in the workspace error in Eclipse
- Debug---Eclipse断点调试基础
- display:inline、block、inline-block的区别
- [JS]_proto_和prototype到底有啥区别
- 超炫的Android高仿知乎日报项目正式开源
- 虚拟化--060 vsphere-vmfs5分区恢复
- linux date命令使用方法
- IOS 宏NSDictionaryOfVariableBindings中的#
- leveldb学习:DBimpl
- spark连接数据库操作(scala实现)
- Linux Shell 通配符、转义字符、元字符、特殊字符
- 面试题
- 虚拟化--059 vmotion真正意义
- 网络营销着陆页:怎么让游客成顾客?
- PLSQL Developer连接Oracle11g 64位数据库配置详解
- 每天进步一点点——优化order by 语句
- 虚拟化--058 vsphere client登录界面中英文切换-
- eclipse设置打开jsp的默认方式