mysql条件&&聚合

查询

条件

  • 使用where进行筛选,结果为true的行会出现在结果集中。
  • 语法如下
    1
    select * from tableName where 条件

比较运算符

  • 等于 = 数据库中等于与编程语言中的区别是等于并不是两个等号
  • 大于 >
  • 大于等于 >=
  • 小于同上
  • 不等于 != 或 <>
  • 查询编号大于3的学生
    1
    select * from tableName where id>3;
  • 查询姓名不是黄蓉的学生

    1
    select * from tableName where sname!='黄蓉';
  • 查询没被删除的学生

    1
    select * from tableName where isdelete=0;

逻辑运算符

  • and
  • or
  • not
  • 查询编号大于3的女同学
    1
    select * from tableName where id>3 and gender=0;

模糊查询

  • like
  • % 表示任意多个字符
  • _ 表示任意一个字符
  • 查询姓黄的学生

    1
    select * from tableName where sname like '黄%';
  • 查询姓黄且名字为一个字的学生

    1
    select * from tableName where sname like '黄_';
  • 查询姓黄或者名字叫做靖的学生

    1
    select * from tableName where sname like '黄%' or sname like '%靖%';

范围查询

  • in表示在一个非连续的范围
  • 查询编号id是1或3或8的学生,一样可以用 or 来实现

    1
    select * from tableName where id in(1,3,8);
  • between … and … 表示在一个连续的范围

    1
    select * from tableName where id between 2 and 5;
  • 查询编号id是3至8的男生

    1
    select * from tableName where id between 3 and 8 and gender=1;

空判断

  • 注意 null 与 ‘’ 是不同的。
  • 判空 is null
  • 查询没有地址的学生

    1
    select * from tableName where hometown is null;
  • 查询填写了地址的学生

    1
    select * from tableName where hometown is not null;
  • 查询填写了地址的女生

    1
    select * from tableName where hometown is not null and gender=0;

优先级

  • 小括号, not, 比较运算符, 逻辑运算符。大体都一致。

聚合

  • 为了快速得到统计数据,提供了 5 个聚合函数。
  • count() 表示计算总行数,括号中写与列名结果一样。
  • 查询有多少个学生

    1
    select count(*) from tableName;
  • 求此列数据中的最大值

  • 如查询女生的编号id最大值,有一个条件性别为女生

    1
    select max(id) from tableName where gender=1;
  • 求此列数据的最小值

  • 如查询未删除学生的最小编号

    1
    select min(id) from tableName where isdelete=0;
  • 查询此列之和

    1
    select sum(id) from tableName;
  • 查询此列平均值

  • 查询此列未删除女生的id平均值,两个条件,性别女生,未删除。
    1
    select avg(id) from tableName where gender=1 and isdelete=0;
文章作者: Luo Jun
文章链接: /2018/04/12/mysqlcoll/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Aning