SQL Select語句完整的執行順序:
1、from子句組裝來自不同數據源的數據;
2、where子句基於指定的條件對記錄行進行篩選;
3、group by子句將數據划分為多個分組;
4、使用聚集函數進行計算;
5、使用having子句篩選分組;
6、select 計算所有的表達式;
7、使用order by對結果集進行排序。
表的完整數據信息是:

完整語法是:
Select [select選項] 字段列表[字段別名]/* from 數據源 [where 字句] [group by子句 ][having 子句][order by 子句][limit 子句];
①[select選項]:
Select 選項包含:ALL(所有,默認)、distinct(去重)。其中distinct針對的是查詢結果的整條記錄而言的。
select DISTINCT(sex) from my_student;

select DISTINCT(sex),name from my_student; 和 selectDISTINCT sex,name from my_student;結果是一樣的。

②[where 子句]:where是唯一一個從磁盤開始拿數據的時候就開始進行判斷的條件,從磁盤取出一條記錄,開始進行where判斷,判斷結果如果成立,那么取出結果保存到內存,否則放棄。
select * from my_student where name = '哈哈1';

③[group by 子句 ]:分組子句,group by子句主要的作用是分組,從而進行統計操作,而不是為了展示(展示的時候,只會展示分組記錄的第一條記錄),分組時,一般會結合使用count()、max()、min()、avg()、sum()函數。
A、單子段分組:
selectc_id,count(*),max(height),min(height),avg(height),sum(age) from my_studentgroup by c_id ;
sql語句的意思是:my_student表以c_id進行分組,然后顯示分組后的每組的c_id名稱、每組的總數、每組的最高、最低、平均身高和每組的年齡總和。
B、多字段分組
select c_id,sex,count(*),max(height),min(height),avg(height),sum(age)from my_student group by c_id ,sex;
表示的含義是,對整個表先按照c_id進行分組,然后在此分組的基礎之上,然后每組再按照sex,進行分組。
C、多字段分組(加上顯示每組的某一字段的所有數據)
selectc_id,sex,count(*),max(height),min(height),avg(height),sum(age) ,GROUP_CONCAT(name)from my_student group by c_id ,sex;
④[having 子句]:having的作用類同where,而且having能做幾乎所有where能做的事情,而where卻不能做having能做的很多事情,主要是因為
where只能在磁盤提取數據的時候對數據進行操作;而在內存中對數據進行group by分組之后的結果進行處理,只能通過having。
selectc_id,count(*),max(height),min(height),avg(height),sum(age) from my_studentgroup by c_id having COUNT(*) >= 3;
⑤[order by 子句]:對數據進行排序操作,根據某個字段進行升序或者降序排序。(進行多字段排序的時候,先根據某一字段進行潘旭,然后在排序好的內部再按照某字段進行排序)
A、單個字段的排序:
select * from my_student order by c_id;

B、多字段排序
select * from my_student order by c_id,sex;

⑥[limit 子句]:限制結果的數量。Limit 偏移量 記錄條數;
A、select * frommy_student limit 2;

B、select * frommy_student limit 0,3;

轉自:https://blog.csdn.net/u011991249/article/details/64519945
