1. 程式人生 > >MySQL 聚合函數、運算符操作、約束

MySQL 聚合函數、運算符操作、約束

使用 數據 like 多個 匹配 非空約束 完整性 一致性 最大

4、聚合函數

1、分類
  avg(字段名) : 求該字段平均值
  sum(字段名) : 求和
  max(字段名) : 最大值
  min(字段名) : 最小值
  count(字段名) : 統計該字段記錄的個數
2、示例
  1、攻擊力最強值是多少
    select max(gongji) from MOSHOU.sanguo;
  2、統計id 、name 兩個字段分別有幾條記錄
    select count(id),count(name) from sanguo;
    ## 空值 NULL 不會被統計,""會被統計

  3、計算蜀國英雄的總攻擊力
    select sum(gongji) from MOSHOU.sanguo


    where country="蜀國";
  4、統計蜀國英雄中攻擊值大於200的英雄的數量
    select count(*) from MOSHOU.sanguo
    where gongji>200 and country="蜀國";

4、運算符操作
  1、數值比較/字符比較
    1、數值比較 := != > >= < <=
    2、字符比較 := !=
    3、練習
      1、查找攻擊力高於150的英雄的名字和攻擊值
        select name,gongji from sanguo where gongji>150;
      2、將趙雲的攻擊力設置為360,防禦力設置為68


        update sanguo set gongji=360,fangyu=68
        where name="趙雲";

5、查詢表記錄時做數學運算
  1、運算符
    + - * / %
  2、示例
    1、查詢時所有英雄攻擊力翻倍
      select id,name,gongji*2 as gj from sanguo;
2、邏輯比較
    1、and (兩個或多個條件同時成立)
    2、or (任意一個條件成立即可)
    3、練習
      1、找出攻擊值高於200的蜀國英雄的名字、攻擊力
        select name as n,gongji as g from sanguo


        where gongji>200 and country="蜀國";
      2、將吳國英雄中攻擊值為110的英雄的攻擊值改為100,防禦力改為60
        update sanguo set gongji=100,fangyu=60
        where country="吳國" and gongji=110;
      3、查找蜀國和魏國的英雄信息
        select * from sanguo
        where country="蜀國" or country="魏國";
3、範圍內比較
1、between 值1 and 值2
    2、where 字段名 in(值1,值2,...)
    3、where 字段名 not in(值1,值2,...)
    4、練習
1、查找攻擊值100-200的蜀國英雄信息
        select * from sanguo
        where gongji between 100 and 200 and
        country="蜀國";
      2、找到蜀國和吳國以外的國家的女英雄信息
        select * from sanguo
        where country not in("蜀國","吳國")
        and sex="女";
      3、找到id為1、3或5的蜀國英雄 和 貂蟬的信息
        select * from sanguo
        where
        (id in(1,3,5) and country="蜀國") or name="貂蟬";
      4、匹配空、非空
        1、空 :where name is null
        2、非空:where name is not null
        3、示例
          1、姓名為NULL值的蜀國女英雄信息
            select * from sanguo
            where
            name is null and country="蜀國" and sex="女";
          2、姓名為 "" 的英雄信息
            select * from sanguo where name="";
        4、註意
          1、NULL :空值,只能用 is 或者 is not 去匹配
          2、"" :空字符串,用 = 或者 != 去匹配
        5、模糊比較
          1、where 字段名 like 表達式
          2、表達式
            1、_ : 匹配單個字符
            2、% : 匹配0到多個字符
          3、示例
          select name from sanguo where name like "_%_";
          select name from sanguo where name like "%";
          ## NULL不會被統計,只能用is、is not去匹配
          select name from sanguo where name like "___";
          select name from sanguo where name like "趙%";

2、約束
  1、作用 :保證數據的完整性、一致性、有效性
  2、約束分類
    1、默認約束(default)
      1、插入記錄,不給該字段賦值,則使用默認值
    2、非空約束(not NULL)
      1、不允許該字段的值有NULL記錄
      sex enum("M","F","S") not null defalut "S"

MySQL 聚合函數、運算符操作、約束