简体   繁体   English

如何提高UNION ALL的MYSQL性能?

[英]How to improve MYSQL performance on UNION ALL?

I am optimizing a query which involves a UNION ALL of two queries. 我正在优化一个涉及UNION ALL两个查询的查询。 Both Queries have been more than optimized and run at less than one second separately. 两种查询都经过优化,并且分别在不到一秒的时间内运行。 However, when I perform the union of both, it takes around 30 seconds to calculate everything. 但是,当我执行两者的并集时,计算所有内容大约需要30秒。

I won't bother you with the specific query, since they are optimized as they get, So let's call them Optimized_Query_1 and Optimized_Query_2 我不打扰你使用特定的查询,因为它们在获得时进行了优化,所以让我们称之为Optimized_Query_1Optimized_Query_2

Number of rows from Optimized_Query_1 is roughly 100K Optimized_Query_1的行数大约为100K

Number of rows from Optimized_Query_2 is roughly 200K Optimized_Query_2的行数大约为200K

SELECT * FROM (
   Optimized_Query_1
UNION ALL
   Optimized_Query_2
) U 
ORDER BY START_TIME ASC

I do require for teh results to be in order, but I find that with or without the ORDER BY at the end the query takes as much time so shouldn't make no difference. 我确实要求结果按顺序排列,但我发现无论有没有ORDER BY,查询都需要花费尽可能多的时间,所以不应该有任何区别。

Apparently the UNION ALL creates a temporary table in memory, from where the final results are then given, is there any way to work around this? 显然UNION ALL在内存中创建了一个临时表,然后从那里得到最终结果,有什么方法可以解决这个问题吗?

Thanks 谢谢

You can't optimize UNION ALL . 您无法优化UNION ALL It simply stacks the two results sets on top of each other. 它只是将两个结果集叠加在一起。 Compared to UNION where an extra step is required to remove duplicates, UNION ALL is a straight stacking of the two result sets. 相比于UNION当需要额外的步骤来删除重复, UNION ALL是两个结果集的直堆叠。 The ORDER BY is likely taking additional time. ORDER BY可能需要额外的时间。

You can try creating a VIEW out of this query. 您可以尝试从此查询中创建VIEW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM