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

标签 mysql limit union-all

我有一个这样的查询:

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/

相关文章:

php - 加快 PHP 渲染巨大的选择列表

android - Android 和 iOS 的最大文件大小和数量

php - 看起来我们没有 XML 文档

SQL - OR 条件的顺序重要吗?

PHP: Mysql查询麻烦

python - 游标在 PyMySQL 中起什么作用和作用?

mysql - 锁定 MySQL 服务器 - CentOS

MySQL 限制 1 获取随机数 (1,8)

php - MySQL Union 不正确返回表名

mysql - 如何在 UNION ALL 中使用 MySQL UNION