MySQL-----排序、限量与分组
1.排序
注意:desc 是降序 asc是升序,默认升序
单字段排序:查询时仅按照一个字段排序
select *|(字段列表)from 表名order by [ASC|DESC];
如:select id,name,price from sh_goods order By price desc
表示:从sh_goods表中以price 降序排序
多字段排序:需要多个条件查询时排序
select *|(字段列表)from 数据表名 order by 字段1[ASC | DESC]{,字段2 [ASC | DESC]};
如: select id,name,price from sh_goods order by id,price desc;
表示:表sh_goods的id,name,price三行中以先id,后price经行降序排序。
2.限量
对于一次性查询多个记录时,不仅不便于阅读还浪费系统效率,所以提供了一个LIMIT,可以限定记录数量。Limit(限制)
select [select 选项] 字段列表 from 数据表名 [where 条件表达式]
[order by 字段 asc | DESC ] limit 记录数;
如:select id,name,price from sh_goods order by price desc limit 2;
意思:从sh_goods表中的id,name,price三列中以价格降序排序限制查询2个。
3.分组
分组:使用group by根据一个或多个字段分组,字段值相同的为一组,另外对分组的数据可以使用having经行条件筛选
分组统计:在查询数据时在where条件后加group by 即可进行指定字段分组
select [select 选项] 字段列表 from数据表名 [where 条件表达式] gruop by 字段名
注意:gruop by 的字段时字段列表中中选一个或使用聚合函数的非分组字段,若不使用聚合函数的非分组字段则回报语法错误(聚合函数:max())
如:select G_id,max(price) from goods group by G_id
意思:根据G_id经行分组,获得G_id分组中price值最大的那个值
分
分组排序:默认情况下分组字段提供升序排序
select 字段列表 from 数据表名 (where 条件表达式) group by 字段名 asc|desc;
注意:分组排序时不需要使用order by 直接在分组字段后加asc|desc即可
如: select category_id,name,id from goods group by category_id desc;
意思:从goods表中的副id,id,name中以副id经行降序排序分组。查询显示的分组后每组商品id及商品名称。
多分组统计:
select 字段列表 from 数据表名 group by 字段1[asc|desc],字段2[asc|desc];
如:select score,count,group_concat(name),price from goods group by score desc,price ;
意思:从goods表中的score,count,group_concat(name),price 这四个列表中经行分组以score经行分组降序分组,再以price经行升序排序分组。
回溯统计:根据指定字段分组后,系统有自动对分组字段向上经行了新的统计并产生一个新的统计数据,且该数据对应的分组字段值为NULL
select 字段列表 from 数据表名 group by 字段1[asc|desc],字段2[asc|desc] with rollup(归纳);
如:select score,count,group_concat(name),price from goods group by score desc,price with rollup ;
意思:从goods表中的score,count,group_concat(name),price 这四个列表中经行分组以score经行分组降序分组,再以price经行升序排序分组,最后对获取的每组数量经行累加统计。
注意:同一个查询语句中回溯统计【with roolup】与排序【order by】只能出现一次
统计筛选:可以利用having根据条件经行数据筛选与where功能相同。
Where与having区别:
1.Where操作是数据表中获得数据,将数据从磁盘存储到内存中,having是对已存放在内存的数据经行操作
2.Having位一group by 之后,where位一group by 之前
3.Having关键字后可以使用聚合函数,where不可以使用聚合函数。
4.通常having与group by一起连用经行分组筛选过滤。
查询中使用别名:
select 字段1 [AS]别名1,字段2 [AS]别名2 from表名【AS可以不写省略,空格代替】
如:select category_id AS sid,max(price) max_price from goods group by cid having cid=3 or cid=6;
意思:将goods表中的category_id 改为sid,max(price)改为max_price然后在以cid经行升序排序,在获得cid为3或6的最高price。