When I optimize my 2 single queries to run in less than 0.02 seconds and then UNION them the resulting query takes over 1 second to run.
您的查询包括ORDER BY … LIMIT子句?
如果在UNION之后放置一个ORDER BY … LIMIT,它将被应用于整个UNION,并且在这种情况下不能使用索引.
如果id是主键,则此查询将是即时的:
SELECT *
FROM table
ORDER BY id
LIMIT 1
,但这不会:
SELECT *
FROM table
UNION ALL
SELECT *
FROM table
ORDER BY id
LIMIT 1
Also, a UNION ALL takes longer than a UNION DISTINCT. I would assume allowing duplicates would make the query run faster and not slower.
这也似乎是由于ORDER BY.排序较小的集合比较大的集更快.
Am I really just better off running the 2 queries separately? I would prefer to use the UNION
您需要将结果集排序吗?
如果没有,只需摆脱最后的ORDER BY.