UNION优化limit查询

情到浓时终转凉″ 提交于 2020-01-28 13:55:14
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)

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!