主要是幾個關鍵字的使用。
1、group by
查詢分組,一般在提供一些統計信息時用到,每個分組結果一般取每個分組第一行。
格式:group by aa[,bb];
2、having
擁有的意思,必須使用分組的字段或聚合函數處理過的字段,mysql 對其進行了擴展,可以使用 select 或外部 select 檢索的字段。
常用于 group by 后,對其分組結果進行篩選。
ps:having 與 where 區別
1、使用順序 where > group by > having;
2、使用字段 where 可以使用任意字段;
3、通常習慣 where 比較自由,having 通常與 group by 一起使用。
3、order by
排序。
格式:order by field1 [desc|asc],order by field2 [desc|asc];
默認寫法:order by field1; #此時默認asc
4、limit
截取結果集。
格式:limit n,m; #第n條開始到第m條
兼容寫法(PostgreSQL):limit m offset n;
默認寫法:limit m; #此時n為0
5、union
聯合:一次性將多表數據取出來,在一個結果集中進行操作。
格式:select a1 from b1 union [all] select a2 from b2;
要求兩邊字段數一樣,如果用 union all 表示在結果集中保留所有數據(包括重復數據)。
小結:
如果在SQL語句中上面子句都用到,使用順序是:where 子句 > group by子句 > having子句 > order by子句 > limit子句