• 单表查询


    单表查询

    1.select

    • 通过调用mysql内置函数的返回值来实现查询

      • select user():查询当前用户
      • selelct database():查看当前库
      • select now() : 查看当前时间
    • 表的查询

      • select 字段,字段,字段*数字 from 表名 : 可对指定的多个字段进行查询,并且字段数据可参与四则运算

      • select distinct 字段 from 表名 : 对查询的字段进行去重

      • select concat(字段,'字符串',字段)from 表 : 字符串的拼接,显示格式的设定

      • select concat_wa('分隔符',字段,字段) as 新表名 from 表 : 插入分隔符和重命名查询出的表

      • # select(
        #     case
        #     when emp_name = 'alex' then
        #         concat(emp_name,'BIGSB')
        #     when emp_name = 'jingliyang' then
        #         emp_name
        #     else
        #         concat(emp_name,'sb')
        #     end
        #     ) as new_name
        # from employee;
        

    2.where筛选

    • select * from 表 where 条件

      • 范围查询

        • # > < >= <= = !=/<>
          # between a and b
          # in (1,2,3,4)   n选1
          
      • 模糊查询

        • like
          • %代表任意长度的任意字符,%ing,a%,%d%
          • _一个小下划线代表一个任意字符,可多个一起使用代表多个字符,'__a’
        • regexp
          • ‘^a’ 正则
          • ‘d+’
        • is/is not
          • is null
          • is not null
        • 逻辑运算
          • and
          • or
          • not

    3.分组 group by

    • select * from 表 group by 字段名
    • 对重复率比较高的某个字段进行分组,该字段有多少种可能就分为多少组
    • 有去重的功效
    • 一旦分组后就不能对具体的某一条数据进行操作
    • group_coucat : 只用来做最终的显示,不能作为中间操作其他数据

    4.聚合函数

    • 大部分情况都是和分组一起使用,如果没有分组使用那么默认一张表示一组
    • count(id) / count(*) 计数;每个组对应几条数据
    • max求最大值:组中某字段的最大值
    • min求最小值,这个组中某字段的最小值
    • avg 求平均值
    • sum求和值

    5.having

    • 过滤条件

    •         # select id,emp_name,age from employee having age>20;
              # select id,emp_name from employee group by age having age>20;
      

      如果后面的条件包含某字段,在显示的字段列表和分组依据的列表必须有一个是该字段,如上

    6.order by

    • order by 字段 :默认升序
    • order by 字段 asc:手动设置升序
    • order by 字段 desc:手动设置降序
    • order by 字段 desc,字段 desc,按先后两个字段排序

    7.limit

    • 显示分页
      • limit m,n : 表示从m+1条数据开始,取n条数据
      • limit n offset m:和上面一样,写法不同
    • 取前n名
      • llimit n 此时m默认是0,表示从第0+1条数据开始,取n条,也就是前n名

    总结

    • 一条分组聚合查询语句的写法顺序,从上到下.

    • # select 想要的列 from 表
      # where 先从这张表中查询的行
      # group by 分组
      # having 对组过滤
      # order by 排序
      # limit 取一个区间
      
  • 相关阅读:
    CPU使用率终极计算
    elementui
    spring security oauth2
    maven bom
    vue jsx
    [spring cloud] feign声明
    加分项
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/W-Y-C/p/11277266.html
Copyright © 2020-2023  润新知