MySQL是否会使ORDER BY子句短路?

时间:2010-04-14 23:58:44

标签: mysql

鉴于此SQL:

SELECT * FROM mytable ORDER BY mycolumn, RAND()

假设mycolumn恰好只包含唯一值(因此包含足够的信息来执行ORDER BY),MySQL是否会使操作短路并跳过评估其余的操作?

2 个答案:

答案 0 :(得分:2)

我认为这就是答案。 Mysql使用不同的计划,不能执行延迟评估(o“hort-circuit”)。

mysql> explain select * from avatar  order by id;
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
| id | select_type | table  | type  | possible_keys | key     | key_len | ref  | rows  | Extra |
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
|  1 | SIMPLE      | avatar | index | NULL          | PRIMARY | 8       | NULL | 28777 |       |
+----+-------------+--------+-------+---------------+---------+---------+------+-------+-------+
1 row in set (0.00 sec)

mysql> explain select * from avatar  order by id, name;
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra          |
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 28777 | Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+----------------+
1 row in set (0.00 sec)
mysql> explain select * from avatar  order by id, RAND();
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows  | Extra                           |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
|  1 | SIMPLE      | avatar | ALL  | NULL          | NULL | NULL    | NULL | 28782 | Using temporary; Using filesort |
+----+-------------+--------+------+---------------+------+---------+------+-------+---------------------------------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

经验表明,即使mycolumn是主键,它也没有。