MySQL数据排序与分组
一、数据排序:order by 用法:select 字段列表 from 表名 [where…] order by 字段名; order by 默认按字段数据的升序排列
降序:desc (放在字段名之后) 升序:asc
如:
select * from xxb1 order by 学号;
select * from xxb1 where 学号>=2 order by 学号 desc;
1、order by 放在select最后 2、order by可用别名 如:
select no 学号, name 姓名 from stu where age>20 order by 学号;
3、order by 复合排序 如:
select * from stu order by age,on;
Select * from stu order by age,on desc;
注意:desc要紧跟前面字段名
例1 查询年龄一条最大、最小数据: 年龄最大:
select * from stu order by age limit 1;
年龄最小:
select * from stu order by age desc limit 1;
例2 查询1号、31号、15号出生的人员信息并按此(几号)降序排序
select 出生日期,right(出生日期,2) as 号数 from xxb1 where right(出生日期,2) in(‘01’,’15’,’31’) order by right(出生日期,2) desc;
二、分组:group by 只要select存在聚合函数、同时存在字段(多值数据)一定要在from之后加分组group by字段。除了聚合函数之外的函数/字段名都要放在group by之后。聚合函数不能放在where中。
用法:select 分组项1[,分组项2],分组表达式 from 表where 筛选条件group by 分组项1[,分组项2] having过滤分组; 如:
select count(*),left(name,1) from xxb1 group by left(name,1);
select avg(id),name from c1 group by id;
三、having(相当于where)放在group by之后 作用:作为聚合函数的用法 如:having count(*)>1;
select province, sex,count(cname) from users group by province, sex having count(cname)>3;