如何限制 UNION ALL 查询的结果?

How to limit the result of UNION ALL query?

我有这样的查询:

select col1, col2 from table1 where col1 = ?
union all
select col1, col2 from table2 where col2 = ?

现在我需要限制上面查询的结果,现在我想知道,如果我在第二个select之后使用limit子句,那么只是第二个[=14=的结果] 将被限制或两者的结果 select?

无论如何,哪种方法适合限制 union all 查询的结果?

一个:

select col1, col2 from table1 where col1 = ?
union all
select col1, col2 from table2 where col2 = ?
limit ?,10

两个:

select * from
    (
    select col1, col2 from table1 where col1 = ?
    union all
    select col1, col2 from table2 where col2 = ?
    ) x
limit ?,10

从性能的角度来看,第一个更好。第二个具体化子查询,这是额外的开销。

注意:您使用的 limit 没有 order by,因此查询的一次执行与下一次执行的结果可能不一致。

您应该使用 order by,这可能与您使用哪个版本无关(因为 order by 无论如何都需要读取和写入数据)。

根据MySQL manual

To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one.

因此,您可以使用:

(select col1, col2 from table1 where col1 = ?)
union all
(select col1, col2 from table2 where col2 = ?)
LIMIT ?, 10

使用子查询也应该有效,但与上述查询相比效率再高不过了。