EXPLAIN SYNTAX SELECT a.UserID, b.VisitID, a.URL, b.UserID FROM hits_v1 AS a LEFTJOIN ( SELECT UserID, UserID as HaHa, VisitID FROM visits_v1) AS b USING (UserID) limit 3;
// 返回优化语句: SELECT UserID, VisitID, URL, b.UserID FROM hits_v1 AS a ALLLEFTJOIN ( SELECT UserID, VisitID FROM visits_v1 ) AS b USING (UserID) LIMIT 3
4. 谓词下推
当 group by 有 having 子句,但是没有 with cube、with rollup 或者 with totals 修饰的时候,having 过滤会下推到 where 提前过滤。谓词下推优化规则涉及到一个参数 enable_optimize_predicate_expression,默认是1,打开谓词下推,设置为 0 就会关闭谓词下推优化。例如下面的查询,HAVING name 变成了 WHERE name,在 group by 之前过滤:
1 2 3 4 5 6 7 8 9 10 11
EXPLAIN SYNTAX SELECT UserID FROM hits_v1 GROUPBY UserID HAVING UserID ='8585742290196126178';
// 返回优化语句 SELECT UserID FROM hits_v1 WHERE UserID ='8585742290196126178' GROUPBY UserID
EXPLAIN SYNTAX SELECT*FROM ( SELECT * FROM ( SELECT UserID FROM visits_v1) UNIONALL SELECT * FROM ( SELECT UserID FROM visits_v1) ) WHERE UserID ='8585742290196126178'
// 返回优化后的语句 SELECT UserID FROM ( SELECT UserID FROM ( SELECT UserID FROM visits_v1 WHERE UserID ='8585742290196126178' ) WHERE UserID ='8585742290196126178' UNIONALL SELECT UserID FROM ( SELECT UserID FROM visits_v1 WHERE UserID ='8585742290196126178' ) WHERE UserID ='8585742290196126178' ) WHERE UserID ='8585742290196126178'
5. 聚合计算外推
聚合函数内的计算,会外推,例如:
1 2 3 4 5 6 7 8 9 10 11
EXPLAIN SYNTAX SELECT sum(UserID *2) FROM visits_v1
// 返回优化后的语句 SELECT sum(UserID) *2 FROM visits_v1
6. 聚合函数消除
如果对聚合键,也就是 group by key 使用 min、max、any 聚合函数,则将函数消除,例如:
EXPLAIN SYNTAX WITH ( SELECT sum(bytes) FROM system.parts WHERE active ) AS total_disk_usage SELECT (sum(bytes) / total_disk_usage) *100AS table_disk_usage, table FROM system.parts GROUPBY table ORDERBY table_disk_usage DESC LIMIT 10;