MySQL select操作整理
以年龄作为查询条件
一、条件查询
1、基础:查询20岁的学生
select * from stu where __age=20__( !=、<> )两者都是不等于的意思
2、and:查询20岁,性别为男的学生
select * from stu where __age=20__ and __sex='男'__
3、between:查询18-20岁的学生
select * from stu where __age__between__18__and__20__
4、or:查询18或者20岁的学生
select * from stu where __age=20__ or __age=18__
select * from stu where __age in (18,20)__
5、查询空:查询年龄项为空的学生
select * from stu where __age is (not) null__
(判断空的时候不能用 “=” ,要用is null和is not null来判断)
6、1. 查询姓'马'的学员信息
select * from stu where name like '马%';
2. 查询第二个字是'花'的学员信息
select * from stu where name like '_花%';
3. 查询名字中包含 '德' 的学员信息
select * from stu where name like '%德%';
二、排序查询
* ASC:升序排列(默认值)
* DESC:降序排列
1.查询学生信息,按照年龄升序排列
select * from stu _order by_ age ;
2.查询学生信息,按照数学成绩降序排列
select * from stu _order by_ math _desc_ ;
3.查询学生信息,按照数学成绩降序排列,如果数学成绩一样,再按照英语成绩升序排列
select * from stu _order by_ math _desc_ , english asc ;
三、分组查询
1. 查询男同学和女同学各自的数学平均分
select sex, avg(math) from stu group by sex;
-- 注意:分组之后,查询的字段为聚合函数和分组字段,查询其他字段无任何意义
select name, sex, avg(math) from stu group by sex;
2. 查询男同学和女同学各自的数学平均分,以及各自人数
select sex, avg(math),count(*) from stu group by sex;
3. 查询男同学和女同学各自的数学平均分,以及各自人数,要求:分数低于70分的不参与分组
select sex, avg(math),count(*) from stu where math > 70 group by sex;
4. 查询男同学和女同学各自的数学平均分,以及各自人数,要求:分数低于70分的不参与分组,分组之后人数大于2个的。
select sex, avg(math),count(*) from stu where math > 70 group by sex having count(*) > 2;
四、分页查询
1. 从0开始查询,查询3条数据
select * from stu limit 0 , 3;
2. 每页显示3条数据,查询第1页数据
select * from stu limit 0 , 3;
3. 每页显示3条数据,查询第2页数据
select * from stu limit 3 , 3;