1. 程式人生 > >Mysql----SQL查詢

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;