結果集排序(查詢排序):
格式:select * from 表名 order by age 參數;
參數:order by:指定排序字段
asc:升序,默認方式
desc:降序
說明:多字段排序:當前面字段值一樣時,按照後面指定的字段進行排序
栗子:select * from 表名 order by sex asc, age desc;
限制結果集(查詢並限制結果數量):
格式:select * from 表名 limit 數量;
參數:指定偏移量(offset)
說明:limit:用於限制結果的數量
示例:select * from 表名 limit num1 offset num2;
select * from 表名 limit 偏移量, 限制量;
分頁查詢(上面最後一條語句):
第一頁:limit 10
第二頁:limit 10, 10
第三頁:limit 20, 10
page頁:limit (page-1) * pageSize(偏移量), pageSize(限制量)
查詢並統計:
select 函數(*) from 表名 where age > 20;
常用聚合函數:
count 統計個數
sum 求和
avg 平均值
max 最大值
min 最小值
分組及過濾:
格式:select * from 表名 group by sex;
參數:group by :根據某個條件排序
示例:select * from 表名 group by sex; # 只分組,結果集中每個組中只有一條數據
select count(*) as c, sex from 表名 group by sex; # 分組並統計信息
select count(*) as c, province from 表名 group by sex having age>20;
說明:分組後條件不能使用where,只能使用having;
having做的是分組後的結果集顯示(過濾),where做的是分組前的數據集條件過濾。