zoukankan      html  css  js  c++  java
  • MYSQL

    一、MySQL普通查询

      

       3、select ...聚合函数 from 表名
        1、where ...
        2、group by ...
        4、having ...
        5、order by ...
        6、limit ...;
      代码的执行顺序按照编号的顺序

    - **聚合函数**

    | 方法          | 功能                 |
    | ------------- | -------------------- |
    | avg(字段名)   | 该字段的平均值       |
    | max(字段名)   | 该字段的最大值       |
    | min(字段名)   | 该字段的最小值       |
    | sum(字段名)   | 该字段所有记录的和   |
    | count(字段名) | 统计该字段记录的个数 |
    |               |                      |
    eg1 : 找出表中的最大攻击力的值?
    
    ```mysql
        select max(attact) from sanguo;
    ```
    eg2 : 表中共有多少个英雄?
    ```mysql
        select count(name) from sanguo;
    ```
    eg3 : 蜀国英雄中攻击值大于200的英雄的数量
    ```mysql
        select count(name) from sanguo where country="蜀国" and attact>200;    

    - **group by**

    给查询的结果进行分组
    eg1 : 计算每个国家的平均攻击力
    
    ```mysql
        select country,avg(attack) from sanguo group by country;   
    ```
    eg2 : 所有国家的男英雄中 英雄数量最多的前2名的 国家名称及英雄数量
    
    ```mysql
        select country,count(id) as number from sanguo where gender ="m" group by country order by number DESC limit 2; 
    ```
    ​    ==group by后字段名必须要为select后的字段====查询字段和group by后字段不一致,则必须对该字段进行聚合处理(聚合函数)==

    - **having语句**

    - **having语句**
    对分组聚合后的结果进行进一步筛选
    ```mysql
    eg1 : 找出平均攻击力大于105的国家的前2名,显示国家名称和平均攻击力
    ```  select country,avg(attack) as att from sanguo group by country having att>105 order by att DESC limit 2   
        where 后面不能跟聚合函数
    注意
    ```mysql
    having语句通常与group by联合使用
    having语句存在弥补了where关键字不能与聚合函数联合使用的不足,where只能操作表中实际存在的字段,having操作的是聚合函数生成的显示列

    - **distinct语句**

    不显示字段重复值
    
    ```mysql
    eg1 : 表中都有哪些国家
        select distinct country from sanguo; 
    eg2 : 计算蜀国一共有多少个国家
    ```    select count (distinct country) from sanguo;
    注意
    ```mysql
    distinct和from之间所有字段都相同才会去重
    distinct不能对任何字段做聚合处理

    - **查询表记录时做数学运算**

    运算符 : +  -  *  /  %  **
    ```mysql
    查询时显示攻击力翻倍
        select name,attact*2 from sanguo;
    更新蜀国所有英雄攻击力 * 2
        update sanguo set attact = attact*2 where country = "蜀国";
  • 相关阅读:
    03.移除相同的元素
    02.计算数组元素之和
    01-找出元素在数组中的位置
    node.js中Content-Type的设置
    node.js接受form表单数据
    node.js创建服务器
    mongoDB笔记
    TDK三大标签SEO(搜索引擎优化)优化
    引入网页图标
    JavaScript实现二叉搜索树
  • 原文地址:https://www.cnblogs.com/Acekr/p/11027548.html
Copyright © 2011-2022 走看看