Mysql Union time V.S. separate query one by one [closed]

泄露秘密 提交于 2019-12-20 07:27:42

问题


If I have n queries q1, q2, q3 ... qn and each of them running t1, t2, t3 ... tn as the running time.

Also I have another query q1 UNION ALL q2 UNION ALL q3 .... UNION ALL qn and running time is tu

compare tu and t1+t2+t3+...+tn, which one will be faster in theory? I know doing experiment is the best way to find out, but I need to hear specialist voice on the theory. Thanks


回答1:


The UNION operator requires duplicate tuples (rows) be removed the result set before any rows are returned. That's effectively a SORT UNIQUE operation. That's relatively inexpensive for small result sets, but for massive sets, it can be resource intensive on the server time (i.e. take a long time.)

In theory, combining the queries with a UNION ALL operator rather than a UNION operator would be fastest, since it would eliminate (n-1) roundtrips to the database, vs running queries separately. But for large values of n, you are going to run into practical limits on the size of the SQL text (max packet size).

Given the choice between UNION operator and separate queries, for a large result set, the separate queries are going to be less resource intensive on the server side.

In short, it's really a tradeoff between the heavy lifting for each query, vs. the heavy lifting of a SORT UNIQUE operation.




回答2:


Since UNION ALL with n subqueries could be executed as n selects, a smart DBMS should be able do at most the same work as n separate selects.

That leaves round trip time, which is n * rtt for n queries and rtt for the UNION ALL.

In theory, a smart DBMS should always be answer a single UNION ALL faster than n separate queries.
In practice, as usual, all bets are off without testing.



来源:https://stackoverflow.com/questions/12590596/mysql-union-time-v-s-separate-query-one-by-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!