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)
可以从一定程度上优化查询。
来源:https://www.cnblogs.com/wooluwalker/p/12237863.html