MySQL 数据查询语言(DQL)

ernestwang 843 0

数据查询语言(DQL)

  • 基本查询:select * from star;
  • 指定字段查询:select name, money from star;
  • 过滤重复记录:select distinct age, sex from star;
    • 说明:distinct指定的字段不能重复,若指定多个字段,则多个字段的组合不能重复
  • 条件查询
    • 条件:
    条件 说明
    > 大于
    >= 大于等于
    < 小于
    <= 小于等于
    = 等于
    != 或 <> 不等于
    and 并且
    or 或者
    [not] between m and n [不]在[m, n]区间内
    [not] in () [不]在指定集合中
    [not] like 条件 模糊匹配,%表示任意字符
    is [not] NULL 是否为NULL
    • 示例:
    select * from star where age>35;
    select * from star where age>30 and age<40;
    select * from star where age between 30 and 40;
    select * from star where id in(2, 4, 6);
    select * from star where province like '%江';
  • 结果集排序
    select name, money from star order by money [asc];  # 升序,默认的可以省略
    select name, money from star order by money desc;   # 降序
    select name, age, money from star order by age asc, money asc;  # 多字段排序
    • 说明:
      • asc表示升序,是默认方式,可以省略,desc表示降序
      • 多字段排序时,先按照前面的排序,前面的值一样按照后面的排序
  • 限制结果集
    • 示例:
    select * from star limit 3;             # 提取3条数据
    select * from star limit 3 offset 2;        # 跳过2条,提取3条数据
    select * from star limit 2, 3;      # 功能同上
    • 分页:
    每页pagesize=10,page表示当前页面,请写出对应数据的查询限制条件:
    第一页:limit 0, 10
    第二页:limit 10, 10
    第三页:limit 20, 10
    page页:limit (page-1)*pagesize, pagesize
  • 常用聚合函数
    函数 说明
    count 统计个数
    sum 求和
    max 求最大值
    min 求最小值
    avg 求平均值
    • 示例:as可以给字段起别名
    select count(*) as c from star;
    select max(money) as max_money from star;
  • 分组及过滤
    select sex from star group by sex;      # 单独分组没有意义,一般不用
    select count(*) as c, sex from star group by sex;   # 分组并统计
    select count(*) as c, sex from star group by sex having c>2;
    # 分组并统计,然后进行过滤,分组之后不能使用where条件,只能使用having

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~

复制成功
微信号: irenyuwang
关注微信公众号,站长免费提供流量增长方案。
我知道了