> For the complete documentation index, see [llms.txt](https://bohans.gitbook.io/ji-chu/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bohans.gitbook.io/ji-chu/mysql/sql-you-hua/cha-xun-you-hua/chang-yong-sql-de-you-hua/you-hua-union-cha-xun.md).

# 优化 UNION 查询

<mark style="color:blue;">**MySQL 总是通过创建并填充临时表的方式来执行 UNION 查询**</mark>，因此很多优化策略在 UNION 查询中都没法很好地被使用。

<mark style="color:orange;">**经常需要手工地将 WHERE、LIMIT、ORDER BY 等子句“下推”到 UNION 的各个子查询中，以便优化器可以充分利用这些条件进行优化**</mark>（例如，直接将这些子句冗余地写一份到各个子查询）。

<mark style="color:orange;">**除非你确实需要服务器消除重复的行，否则一定要使用 UNION ALL**</mark>，这一点很重要。**如果没有 ALL 关键字，MySQL 会给临时表加上 DISTINCT 选项，这会导致对整个临时表的数据做唯一性检查，这样做的代价非常高。**
