MySQL 中的 UNION 是否依赖于 "SELECT" 的顺序?

Does UNION in MySQL depend on the order of "SELECT"?

我有两个 sql 请求。第一个请求是:

SELECT field_1, field_2
FROM mydb.table_1, mydb.table_2
WHERE TIME > 0 
  AND TIME <= 1460539620031 
  AND table_1_id = table_1.id 
UNION
SELECT field_1, field_2 
FROM mydb.table_1, mydb.table_3
WHERE TIME > 0 
  AND TIME <= 1460539620031 
  AND table_1_id = table_1.id; 

第二个请求是:

SELECT field_1, field_2
FROM mydb.table_1, mydb.table_3
WHERE TIME > 0 
  AND TIME <= 1460539620031 
  AND table_1_id = table_1.id 
UNION
SELECT field_1, field_2 
FROM mydb.table_1, mydb.table_2
WHERE TIME > 0 
  AND TIME <= 1460539620031 
  AND table_1_id = table_1.id; 

它们只是命令的顺序不同"SELECT",但是命令"SELECT"是相同的。但是执行这些请求的结果是不同的:第一个结果集包含的行多于另一个

为什么会这样? MySQL 中的 UNION 是否依赖于 "SELECT" 的顺序?

我假设并集的结果在顺序或并集中。但是,union remove duplicates 因此,它需要在内部(或等效)对事物进行排序。联合的顺序可能会影响此删除重复阶段,并且在大多数情况下,行可能看起来是按照语句的顺序生成的。

取自mysql documentation

However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.

其他情况下,顺序不保证。如果您想要一个特定的顺序,您需要添加一些括号并在末尾放置一个顺序子句。

如果您真的想通过 table 获得结果 groupeb,您可以查看文档中的解决方案。

To cause rows in a UNION result to consist of the sets of rows retrieved by each SELECT one after the other, select an additional column in each SELECT to use as a sort column and add an ORDER BY following the last SELECT:

(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col;

这是因为 SQLyog(我在其中 运行 查询)在查询末尾添加了表达式 "LIMIT 0, 10000"。