1. 程式人生 > >mysql 中同時使用orderby和groupby的分析

mysql 中同時使用orderby和groupby的分析

最近做專案寫sql的時候同時使用到了order by 和 group by.然而查詢出來的結果不是自己想象中的那樣.

下面來分析一樣原因:
mysql 寫sql的順序:
select -> from-> where->group by->having->order by.
但mysql的解析器執行順序:
from-> where->group by->having->select->order by.
所以,從執行的流程來看,是先group by 然後在 order by.
order by拿到的結果裡已經是group by以後的結果.

因此,order by的欄位必須是group by 裡面已經存在的欄位.