2

I know the union all questions gets asked a lot, but I have a slight variation. I will be doing a union all on three different queries/tablesets. The first 2, by definition of their queries, will never have duplicates, but the third will definitely have duplicates.

My question is, does the order I do my union/union alls matter. For instance, should I do a UNION ALL on my first 2 tables that won't have duplicates (and never ever will) and then do a UNION to the third table since it will have duplicates? Or is the order better if its reversed? Or does it not matter?

Not a real pressing matter, just wondering if there was a best practice in this type of scenario.

4

1 回答 1

3

UNION ALL 返回所有行,不进行额外处理。一个简单的 UNION 对整个行集进行排序以消除重复。虽然优化器可能能够通过研究索引和约束来解决所有问题,但您总是可以像这样帮助它:

  select * from table1
union all
  select * from table2
union all
  select *
  from (
    SELECT DISTINCT * from table3
  ) T

这确保了排序和消除重复项仅在 table3 上执行。

任何时候意图都可以简单而清晰地传达给人类用户和编译器,这几乎可以肯定是编写代码的正确方法。在这种情况下,性能也可以提高,而不能降低。

于 2013-03-19T18:35:12.497 回答