-- 聚合函数: max/ min / sum /avg / count -- 查询年龄最大的学生的出生日期(聚合函数) selectmin(birth) from tb_student;
-- 查询年龄最小的学生的出生日期(聚合函数) selectmax(birth) from tb_student;
-- 查询男女学生的人数(分组和聚合函数) selectif(gender,'男','女') 性别, count(gender) 人数 from tb_student groupby gender;
-- 查询课程编号为1111的课程的平均成绩(筛选和聚合函数) selectavg(mark)as 平均成绩 from tb_score where cid = 1111;
-- 查询学号为1001的学生所有课程的平均分(筛选和聚合函数) selectavg(mark) 平均成绩 from tb_score wheresid = 1001;
-- 查询每个学生的学号和平均成绩(分组和聚合函数) selectsid 学号, avg(mark) 平均分 from tb_score groupbysid;
-- 查询平均成绩大于等于90分的学生的学号和平均成绩 selectsid 学号, avg(mark) 平均分 from tb_score groupbysidhaving 平均分>=90;
-- 查询平均成绩大于等于90分的学生且学号为1开头学号的 学号和平均成绩 -- where 用于分组之前的筛选, 分组之后用 having selectsid 学号, avg(mark) 平均分 from tb_score wheresidbetween1000and1999groupbysidhaving 平均分>=90 orderby 平均分 desc;
-- 查询年龄最大的学生的姓名(子查询) select sname 姓名 from tb_student where birth=(selectmin(birth) from tb_student);
-- 查询年龄最大的学生姓名和年龄(子查询+运算) -- 把一个查询的结果当成另一个查询的一部分来使用 select sname 姓名, from tb_student where birth=(selectmin(birth) from tb_student);
-- 查询选了两门以上的课程的学生姓名(子查询/分组条件/集合运算) select sname 姓名 from tb_student where stuid in (selectsidfrom tb_score groupbysidhavingcount(sid)>2)
-- 查询学生姓名、课程名称以及成绩(连接查询) select sname , cname, mark from tb_student, tb_course, tb_score where stuid=sidand couid=cid limit5offset10;
-- 分页查询 select sname 学生姓名, cname 课程名称, mark 考试成绩 from tb_student innerjoin tb_score on stuid=sid innerjoin tb_course on couid=cid limit5offset15;
select sname 学生姓名, cname 课程名称, mark 考试成绩 from tb_student innerjoin tb_score on stuid=sid innerjoin tb_course on couid=cid limit15,5;
-- 查询选课学生的姓名和平均成绩(子查询和连接查询) select sname 姓名, avgmark 平均分 from tb_student t1, (selectsid, avg(mark) as avgmark from tb_score groupbysid) t2 where stuid=sid;
-- 方法二 内连接 select sname 姓名, avgmark 平均分 from tb_student t1 innerjoin (selectsid, avg(mark) as avgmark from tb_score groupbysid) t2 on stuid=sid;
-- 左外连接:将左表不满足连表条件的记录查出来 不满足连表条件的地方补null -- 右外连接:将右表不满足连表条件的记录查出来 不满足连表条件的地方补null -- 在连接多表查询时写在前面的表称为左表,写在后面的表称为右表 -- left outer join / right outer join -- outer可以省略 -- MySQL不支持全外连接 full outer join select sname as 姓名, ifnull(total, 0) as 选课数量 from tb_student t1 leftouterjoin (selectsid, count(sid) as total from tb_score groupbysid)t2 on stuid=sid;