我有一个这样的查询:
select col1, col2 from table1 where col1 = ?
union all
select col1, col2 from table2 where col2 = ?
现在我需要限制上述查询的结果,现在我想知道,如果我在第二个 select
之后使用 limit
子句,那么只是第二个查询的结果select
会受到限制还是同时 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
最佳答案
根据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
使用子查询也应该可以,但与上面的查询相比效率不会更高。
关于mysql - 如何限制UNION ALL查询的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33067102/