码迷,mamicode.com
首页 > 其他好文 > 详细

UNION优化limit查询

时间:2020-01-28 13:47:35      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:pos   row   col   span   last   tab   cto   mysql   weight   

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查询

标签:pos   row   col   span   last   tab   cto   mysql   weight   

原文地址:https://www.cnblogs.com/wooluwalker/p/12237863.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!