2010-04-14 59 views
3

鑑於這種SQL:MySQL是否將ORDER BY子句短路?

SELECT * FROM mytable ORDER BY mycolumn, RAND() 

假設mycolumn恰好只包含唯一的值(因此,包含足夠的信息來執行ORDER BY),確實MySQL的短路操作並跳過評估休息嗎?

+0

邪惡的問題,從來沒有想過,即使是可能的,不管底層DBMS的 – LorenVS 2010-04-15 00:01:38

+0

只需花15分鐘通過PostgreSQL的源代碼,翻錄,似乎無法找出任何確切的答案:(甚至不會回答儘管你對mysql的問題,我會檢查這個雖然 – LorenVS 2010-04-15 00:15:24

+0

這將是一個不尋常的優化 - 通常,對多個列的ORDER BY將形成基於第一列的行組,然後進一步根據第二列對這些組進行排序等。鑑於這是預期的常用用法,爲什麼他們會針對不同的用法進行優化(其中多餘的列顯然是多餘的) – 2010-04-16 13:34:10

回答

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) 
0

經驗表明它不會,即使mycolumn是主鍵。