2012-10-27 32 views
8

可以說我有一種植物表:集合函數可以在ORDER BY子句中做什麼?

id fruit 
1 banana 
2 apple 
3 orange 

我能做到這

SELECT * FROM plant ORDER BY id; 
SELECT * FROM plant ORDER BY fruit DESC; 

這確實顯而易見的事情。

但是我被這個咬了,這是做什麼的?

SELECT * FROM plant ORDER BY SUM(id); 
SELECT * FROM plant ORDER BY COUNT(fruit); 
SELECT * FROM plant ORDER BY COUNT(*); 
SELECT * FROM plant ORDER BY SUM(1) DESC; 

所有這些只返回第一行(id = 1)。

  1. 發生了什麼事?
  2. 聚合函數將在ORDER BY中派上用場的場景是什麼?

回答

12

你的結果會更清楚,如果你真的從表中選擇彙總值,而不是列:

SELECT SUM(id) FROM plant ORDER BY SUM(id) 

這將返回所有的ID的總和。這當然是無用的例子,因爲聚合總是隻創建一行,因此不需要排序。你在查詢中得到一行qith列的原因是因爲MySQL選擇了一行,不是隨機的,而是不確定的。只是碰巧它是表格中的第一列,而其他的可能會取決於存儲引擎,主鍵等等。因此,僅在ORDER BY子句中的聚合不是很有用。

你通常想要做的是某一個領域分組,然後排序結果以某種方式設置:

SELECT fruit, COUNT(*) 
FROM plant 
GROUP BY fruit 
ORDER BY COUNT(*) 

現在,這是一個更有趣的查詢!這會給你一行每個水果以及該水果的總數。請嘗試將更多的蘋果和訂貨會真正開始做的意義:

完整的表:

+----+--------+ 
| id | fruit | 
+----+--------+ 
| 1 | banana | 
| 2 | apple | 
| 3 | orange | 
| 4 | apple | 
| 5 | apple | 
| 6 | banana | 
+----+--------+ 

上述查詢:

+--------+----------+ 
| fruit | COUNT(*) | 
+--------+----------+ 
| orange |  1 | 
| banana |  2 | 
| apple |  3 | 
+--------+----------+ 
+0

優秀的解釋,謝謝! – nawfal

2
  1. 當您使用這樣的集合體,查詢通過整個結果爲單個組的地方得到隱式組。

  2. 如果您還有一個group by,則只有在結果中可以有多行時才使用聚合。

2

所有這些查詢都會在任何符合SQL標準的SQL平臺上發出語法錯誤。

SELECT * FROM plant ORDER BY SUM(id); 
SELECT * FROM plant ORDER BY COUNT(fruit); 
SELECT * FROM plant ORDER BY COUNT(*); 
SELECT * FROM plant ORDER BY SUM(1) DESC; 

在PostgreSQL上,例如,所有這些查詢都會引發相同的錯誤。

ERROR: column "plant.id" must appear in the GROUP BY clause or be used in an aggregate function

這意味着您正在使用域聚合函數而不使用GROUP BY。 SQL Server和Oracle返回類似的錯誤消息。

至少就標準行爲而言,MySQL的GROUP BY已知在多個方面被破壞。但是你發佈的查詢對我來說是一種新的破壞行爲,所以+1。

與其試圖理解它在底層做什麼,而不是學習編寫標準的GROUP BY查詢。據我所知,MySQL 正確處理標準GROUP BY語句。

早期版本的MySQL文檔警告您關於GROUP BY和隱藏列。 (我沒有一個參考,但這個文本中引用的所有的地方。)

Do not use this feature if the columns you omit from the GROUP BY part are not constant in the group. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.

More recent versions are a little different

You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.

就個人而言,我不認爲不確定 SQL中的功能。

相關問題