文档分值:4

SQL语言基础 >>> SQL语言基础 >>> 排序

课程目录

修改
增加
删除
查询
排序
查看
排序

order by

根据指定的列对结果集进行排序。

排序结果默认为升序,如果需要降序排列,需要使用 desc 关键字

desc 关键字示例:

  • 未使用 desc
select    id,name    from    admin    order    by    id    ;

结果是:

|    id    |    name            |
+----+--------+
|        1    |    gsh                |
|        7    |    admin        |
|    10    |    leo                |
|    11    |    nemo            |
|    12    |    taozi        |
|    13    |    mj001        |
|    14    |    zzl005    |
+----+--------+

加上 desc 关键字后:

select    id,name    from    admin    order    by    id    desc;
+----+--------+
|    id    |    name            |
+----+--------+
|    14    |    zzl005    |
|    13    |    mj001        |
|    12    |    taozi        |
|    11    |    nemo            |
|    10    |    leo                |
|        7    |    admin        |
|        1    |    gsh                |
+----+--------+

抽象SQL 语句(单字段排列):

select    *    from    table_name    order    by    column_name;

上面是针对单字段的排列,也可以根据多个列对结果进行排序,优先顺序按从左到右的列依次降低:

抽象SQL 语句(多字段排列):

select    *    from    table_name    order    by    column_name1,        column_name2,    column_name3;

依次按照column_name1,column_name2column_name3 对结果进行排序

group by

group by 的作用是结合合计函数,根据一个或多个列对结果集进行分组。

如果我们需要查看订单表中每个顾客的所有订单价格

相应的 SQL 语句

SELECT    Customer,SUM(OrderPrice)    FROM    Orders
GROUP    BY    Customer
  • 原则:

group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面。

即在select指定的字段要么就要包含在Group By语句的后面,作为分组的依据;要么就要被包含在聚合函数中

聚合函数有:

  • sum(列名) 求和
  • max(列名) 最大值
  • min(列名) 最小值
  • avg(列名) 平均值
  • count(列名) 统计记录数

group all

sql 语句:

select    cid,uid,count(title)    from    doc    group    by    all    cid,uid;

group by 中 where 和 having 的区别

  • where

错误语句示例:

select    cid,count(title)    from    doc    group    by    cid    where    cid    <    100;

正确的语句为:

select    cid,count(title)    from    doc    where    cid    <    100    group    by    cid;

说明:

  1. where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据
  2. where 条件中不能包含聚组函数
  • having

错误语句示例:

select    cid,count(title)    from    doc    having    count(title)    >    20    group    by    cid;

正确的语句为:

select    cid,count(title)    from    doc        group    by    cid    having    count(title)    >    20;

说明:

  1. having 子句的作用是筛选满足条件的组,即在分组之后过滤数据
  2. 条件中经常包含聚组函数,使用 having 条件过滤出特定的组,也可以使用多个分组标准进行分组。

总结:

  • where 子句用在 group by 语句之前,用来在分组之前过滤数据
  • having 子句用在 group by 语句之后,用来在分组之后过滤数据

[ 该条目创建时间:2016-06-25 09:09:58 ]