简体   繁体   中英

MySQL UNION ALL performance tuning

SELECT `col1` FROM `tbl1`;   -- takes 0.0022s

SELECT `col1` FROM `tbl2`;   -- takes 0.0017s

SELECT `col1` FROM `tbl1`
UNION ALL 
(SELECT `col1` FROM `tbl2`); -- takes 0.1100s

Why UNION ALL working slow?

Any other alternative of using UNION ALL ?

Is the Query Cache turned on? It could be that the two individual SELECTs are artificially fast due to getting the resultset from the QC.

Let's dissect the UNION to understand its sluggishness:

  1. Create a temp table for the resultset.
  2. Perform first SELECT , writing results to that temp.
  3. Perform second SELECT , writing results to that temp.
  4. Read the temp table.
  5. (De-duplicate. This did not happen since you said ALL on UNION .)
  6. Deliver the results to the client.
  7. Drop the temp table.

Two things are probably aggravating the situation:

  • Windows is slower than *NIX at building tables.
  • It was not until a very recent versions of MySQL that some UNIONs can avoid the temp table. That is, in the future, the results from each SELECT can be delivered directly to the client. You apparently do not have such version.

As for the parentheses, leave them on. Put them on the other SELECT , too. It does not impact performance, but it may impact the result. Imagine, for example, what the GROUP BY applies to in these three cases:

-- Case 1
SELECT ..     UNION SELECT ..   GROUP BY ..

-- Case 2
SELECT ..     UNION ( SELECT ..   GROUP BY .. )

-- Case 3
( SELECT .. ) UNION ( SELECT .. ) GROUP BY ..

The first one is the same as the second, not the third.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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