网络编程-Mysql-2、各种查询

1、先创建一个学生表

create table students (

id int auto_increment not null primary key,

name varchar(20)  not null,

age int unsigned default null,

height decimal(5,2) default null,

gender enum('男','女','保密') default '保密',

cls_id int unsigned default 0

);

在创建一个班级表

create table classes (

id int unsigned not null primary key,

name varchar(20) not null

);

2、逻辑运算符

     (1)查询编号大于3的女同学:select * from students where id > 3 and gender=0;

     (2)查询编号小于4或年龄大于20的学生:select * from students where id < 4 or age>20;

3、模糊查询

      (1)查询姓黄的学生:select  *  from students where name like '黄%';

   (2)查询姓黄并且“名”是一个字的学生:select  *  from students where name like '黄_';

   (3)查询姓黄或叫靖的学生:select  * from students where name like '黄%' or name like '%靖';

4、范围查询

  (1)查询编号是1或3或8的学生(非连续范围):select * from students where id in(1,3,8);

  (2)查询编号为3至8的学生(连续范围查询):select * from students where id between 3 and 8;

5、空判断

  (1)查询没有填写身高的学生:select * from students where height is null;

  (2)查询填写了身高的学生:select * from students where height is  not null;

  (3)查询填写了身高的男生:select * from students where height is not null and gender='男';

6、排序

    注解:将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推默认按照列值从小到大排列(asc)asc从小到大排列,即升序desc从大到小排序,即降序

  (1)显示所有的学生信息,先按照年龄从大-->小排序,当年龄相同时 按照身高从高-->矮排序:select * from students order by age desc,height desc;

7、聚合函数

  (1)查询学生总数:select  count(*)  from students;

  (2)查询女生的编号最大值: select max(id)  from students where gender='女';

  (3)查询男生的编号最小值: select min(id)  from students where gender='男';

  (4)查询男生的总年龄: select sum(age) from students where gender='男;

  (4)查询未年龄大于20的女生的编号平均值: select avg(id)  from students where age>20 and gender='女';
8、分组

  (1)查询性别为男的平均年龄,总人数,以及包含哪些人:select gender,count(*),avg(age),group_concat(name) from studetns group by gender having gender=1;

9、连接查询

         内连接查询(取俩个表的交集,没有则不显示)

  (1)查询每个学生对应的班级:select * from studetns as s inner join classes c on s.cls_id=c.id;

   左连接查询(已左表为基准)

  (2)查询每个学生对应的班级:select * from studetns as s left join classes c on s.cls_id=c.id;

  右连接查询

  (3)查询每个学生对应的班级: select * form studetns as s right join classes on s.cls_id=c.id;

10、分页查询

  (1)查询第二页,每页显示2个:select * from studetns limit 2,2;

原文地址:https://www.cnblogs.com/lz-tester/p/9517544.html