UNION优化limit查询

Posted wooluwalker

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UNION优化limit查询相关的知识,希望对你有一定的参考价值。

mysql> explain
    -> (select first_name,last_name from sakila.actor order by last_name)
    -> union all
    -> (select first_name,last_name from sakila.customer order by last_name)
    -> limit 20;
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | PRIMARY     | actor    | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  200 |   100.00 | NULL  |
|  2 | UNION       | customer | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  599 |   100.00 | NULL  |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------+
2 rows in set, 1 warning (0.00 sec)


mysql> explain
    -> (select first_name,last_name from sakila.actor order by last_name limit 20)
    -> union all
    -> (select first_name,last_name from sakila.customer order by last_name limit 20)
    -> limit 20;
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+----------------+
|  1 | PRIMARY     | actor    | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  200 |   100.00 | Using filesort |
|  2 | UNION       | customer | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  599 |   100.00 | Using filesort |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+----------------+
2 rows in set, 1 warning (0.00 sec)

由上面的执行计划可知,两者的影响行数一样,但是加上union子句的limit 20 条限制,可以减少临时中间表中的数据(20+20,而不是 200+599)

可以从一定程度上优化查询。

以上是关于UNION优化limit查询的主要内容,如果未能解决你的问题,请参考以下文章

MySQL基础语法之子链接查询和特殊查询(union 和 limit)

在 MySQL 查询中结合 UNION 和 LIMIT 操作

SQL-子查询;union;limit

MySQL笔记--- 连接查询;子查询;union;limit;

Mysql:使用union all时使用order by和limit到单独的查询

MySql性能优化查询优化