Mysql----SQL查询

   总结

      ①where ...                 [无法操作聚合函数生成的数]
      ②group by...            对查询结果进行分组

      ③select ...                 聚合函数 from 表名
      ④having ...               [操作聚合函数生成的数]
      ⑤order by ...           对查询结果进行排序
      ⑥limit ...                   [执行顺序]

聚合函数

      avg(字段名)   :  求该字段平均值
      sum(字段名)  :  求和
      max(字段名)  :  最大值
      min(字段名)   :  最小值
      count(字段名)  :  统计该字段记录的个数

1)group by

作用:给查询结果进行分组

注意:

  1. group by之后的字段名必须为select之后的字段名
  2. 如果select之后的字段名与group by之后的字段不一致,必须对该字段进行聚合处理(聚合函数)

示例:

      1、查询表中一共有几个国家
        select count(country) from sanguo;

      2、计算每个国家的平均攻击力
        select country,avg(gongji) from sanguo
        group by country;

        
	先分组 -> 再聚合 -> 再去重
        蜀国
	蜀国
	蜀国   --> 120    --> 蜀国
	魏国
	魏国   --> 110    --> 魏国
	吴国   --> 115    --> 吴国
      3、查找所有国家中英雄数量最多的前2名的 国家名称和英雄数量
       select country,count(id) as number from sanguo
       group by country
       order by number desc
       limit 2;

2)having

作用:对查询结果进行进一步筛选(操作聚合函数生成的数)

注意:

  1. having语句通常与group by语句联合使用,过滤由group by语句返回的记录集
  2. where还能操作表中存在的实际的记录,而having可以操作聚合函数生成的显示列
找出平均攻击力>105的国家的前2名,显示国家名和平均攻击力
       select country,avg(gongji) as pjgj from sanguo
       group by country
       having pjgj>105
       order by pjgj DESC
       limit 2;

3)order by

作用:给查询的结果进行排序

语法:  ...order by 字段名 ASC/DESC

             ASC: 升序(默认)

            DESC:降序

示例:

      1、将英雄按防御值从高到低排序
        select * from sanguo order by fangyu DESC;

      2、将蜀国英雄按攻击值从高到低排序
          select * from sanguo where country="蜀国" order by gongji DESC;

      3、将魏蜀两国英雄中名字为三个字的按防御值升序排列
        select * from sanguo 
        where
        country in("蜀国","魏国") and name like "___"
        order by fangyu ASC;

	select * from sanguo
        where
        (country="魏国" or country="蜀国") and name like "___"
        order by fangyu;

4)limit(永远放在SQL语句的最后写)

作用:限制显示查询记录的个数

用法:

  • limit n -----> 显示n条记录
  • limit m,n ------>表示从m+1条开始显示n条记录  (limit 2,3  表示显示3,4,5条记录)

示例:

      1、在蜀国英雄中,查找防御值倒数第二名至倒数第四名的英雄的记录
        select * from sanguo
        where country="蜀国"
        order by fangyu asc
        limit 1,3;

      2、在蜀国英雄中,查找攻击值前3名且名字不为 NULL 的英雄的姓名、攻击值和国家
        select name,gongji,country from sanguo
        where 
        country="蜀国" and name is not NULL
        order by gongji DESC
        limit 3;

分页:

            每页显示n条记录,显示第m页     :    limit  (m-1)*n,n

distinct

作用:不显示重复字段(只能做简单去重不能做聚合)

注意:

  • distinct和from之间所有字段都相同才会去重
  • distinct不能对任何字段做聚合处理

示例:

      1、表中都有哪些国家
        select distinct country from sanguo;

      2、计算蜀国一共有多少个英雄
        select count(distinct id) from sanguo 
        where country="蜀国";

查询表记录时做数学运算

运算符: +    -   *   /    %

示例:

查询时所有英雄攻击力翻倍
        select id,name,gongji*2 as gj from sanguo;

猜你喜欢

转载自blog.csdn.net/py_1995/article/details/84306797