UNION query optimization 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)

Seen from the above implementation plan, as both affect the number of rows, but with union clause 20 Restriction limit, the data can be reduced in the temporary intermediate table (20 + 20, instead of 200 + 599)

Queries can be optimized to some extent.

Guess you like

Origin www.cnblogs.com/wooluwalker/p/12237863.html