模糊查询与分组查询

一:LIKE运算符

  1.用%通配多个字符

    1)查询以“王”开头的学生信息

    select  字段名1,字段名2...... from 表名 where 字段名 like “王%”;

    2)查询含有“王”的学生信息

    select 字段名1,字段名2...... from 表名 where 字段名 like “%王%”;

    3)查询以“王”结尾的学生信息

    seelct 字段名1,字段名2...... from 表名 where 字段名 like“%王”;

  2.用_通配单个字符(英文条件下的下划线)

    1)查询姓王的“王_”(2个字符)

    select 字段名1,字段名2...... from 表名 where 字段名 like“王_”;

    2)查询姓王的“王__”(三个字符)

    select 字段名1,字段名2...... from 表名 where 字段名 like“王__”;

    3)查询以“_王”结尾的学生信息

    select 字段名1,字段名2...... from 表名 where 字段名 like“_王”;

  3.%与_混合使用

    查询第二个字为“王”的学生信息

    select 字段名1,字段名2...... from 表名 where 字段名 like“_王%”;

二:聚合函数

  1.SUM

    select  SUM(字段名)from  表名 where 条件

    select  SUM(score)from  EXAM where id=" ";

  2.MAX/MIN

    select  MAX/MIN(字段名)from  表名 where 条件

    select  MAX/MIN(score)from  EXAM where id=" ";

  3.AVG

    select  AVG(字段名)from  表名 where 条件

    select  AVG(score)from  EXAM where id=" ";

  4.count(*)计算数据表或查询结果集的总行数,不管某一列或多列是否为空值

    select count(*)from 表名;

三:分组查询

  1.GROUP BY+ORDER BY+MIN/MAX

  select 字段名1,字段名2......from  表名 GROUP BY 字段名1;//根据字段名1分组查询字段2

  select ClassID,count(*) from student GROUP BY ClassID;

  select ClassID,count(*) from student GROUP BY ClassID ORDER BY MIN/MAX(字段名)ASC/DESC;//ASC/DESC升序/降序

  2.多列分组查询

  select 字段名1,字段名2,字段名3...... from 表名 GROUP BY 字段名1,字段名2;

  select ClassID,Gender,Count(*) from student GROUP BY ClassID,Gender;

  3.Having子句—分组查询的条件筛选

  select 字段名1,字段名2 from 表名 GROUP BY 字段名1 Having 字段名2条件 ORDER BY 字段2条件

  select ClassID,MIN(score) from EXAM GROUP BY ClassID Having  MIN(score)>60  ORDER BY  MIN(score) ASC;

  select name,length(name),now() from 表名//查询姓名,姓名长度,系统当前时间

  select * from 表名 GROUP BY address Having AVG(avg)>20 like 1;//按地址分组后,找出平均年龄大于20的那个组内第一行值。

  select * from 表名 where id>5  GROUP BY address Having AVG(avg)>20 like 1;//按地址分组后,找出平均年龄大于20的那个组内id>5的第一行值

  select * from 表名 GROUP BY address Having AVG(avg)>20 ORDER BY ASC/DESC  like 1;//按地址分组后,找出平均年龄大于20的那个组内的第一行值并把年龄升序排列

猜你喜欢

转载自www.cnblogs.com/W19990605/p/11567952.html