1. 程式人生 > 其它 >mysql where group by having order by執行優先順序順序

mysql where group by having order by執行優先順序順序

where、group by、having、order by、limit 用法也是這個順序排列,在一個語句裡不允許上述排序的後面的語法出現在前面語法。

where:定位
group by:分組
having:對查詢結果的臨時表進行篩選操作
order by:排序 預設升序,也可以加asc 加desc就是降序
limit:限制條目

select xx from xx where xx group by xx order by xxx;
select xx from xx group by xx having xx order by xxx;

where 跟having 後面都可以跟條件。但是又有很多區別
1 where 的欄位必須是表中的欄位
2 執行順序是,先where 後 聚合
3 having 後面的欄位不必須是表的欄位
4 having 先聚合 後 條件
5 有時where 跟having 可以替換
6.group by 分組屬性 having 分組過濾的條件,這個是按照分組屬性進行分組,所有分組屬性上值相同的記錄被分為一組,作為結果中的一條記錄,後面的having是對分組進行過濾的條件,必須和group by一起使用

distinct 跟group by的區別
兩個的效果是一致的.都是返回相同的一條。但是。其實他們是不一樣的。
1 distinct 是把重複行的資料剔除,只顯示一條
2 group by 是分組顯示,是聚合