• grade表如下:

image.png

  • 查询每门学科均大于80的人
    • 方法1:逆向思维select distinct name from grade where name not in (select distinct name from grade where score<=80); 即先查找有分数小于80的人, 然后这以外的就是均大于80的人)
    • 方法2:select name from grade group by name having min(score)>80;查询一个人三个科目中最小分数大于80的人
      • 方法3:查询一个人分数总和大于180的人,和方法二是一个套路
  • 查询平均分大于80的人并输出平均分select name, avg(score) 平均分 from grade group by name having avg(score)>80;

班级image.png课程image.png成绩image.png学生image.png老师image.png
每个学生选择的课程不一样。平均分就算个人选的课程数。 另外就是成绩表中的学生在学生表中一定存在,但是学生表学生不一定会在成绩表中(这关系到采用何种连接方式)
以下都默认不知道每个表的数据的条数情况选择的是最合适的连接方式

  • 查询平均分大于60分的学生,输出学号,姓名,平均分

    1. 显然以成绩表为主,但是我们还需要成绩表的基础上增加一列:学生姓名。所以我们先连接查询,这里因为是以成绩为主,所以我们以有成绩的学生为主,左连接。 在连接后的成绩表基础上通过姓名分组...
    2. select student.sid,avg(number),sname from score left join student on score.student_id = student.sid group by sname having avg(number)>60;
  • 查询所有同学的学号,姓名,选课数,总成绩

    1. 同上,因为这里是要全部学生,所以我们采用右连接
    2. select student.sid,sum(number),sname,count(course_id) from score right join student on score.student_id = student.sid group by sname;
  • 查询姓“李”的老师的个数; 这没有什么好说的,主要注意逻辑上来说count(字段)会更加合适一些,虽然这里count(*)和count(cname)一定相同

    1. select count(tname) from teacher where tname like '李%';
  • 查询没学过“叶平”老师课的同学的学号、姓名 ```sql 因为是匹配没学过,所以score外的都是没学过的。所以右连接 然后course_id为2的以外的都是没学过的
    select distinct student.sid,sname from score right join student on score.student_id = student.sid where student.sid not in(select distinct student.sid from score right join student on score.student_id = student.sid where course_id=2);

select sid,sname from student where sid not in(select student_id from score where course_id in(select cid from course where teacher_id in (select tid from teacher where tname = ‘叶平’)));

一开始采用的是 select distinct student.sid,sname from score right join student on score.student_id = student.sid where course_id<>2 or course_id is null; 这种是不行的,因为成绩表是一个人可以有很多课程,这样仅仅排除了等于course——id为2的一条数据

  1. - **查询学过“叶平”老师所教的所有课的同学的学号、姓名**
  2. ```sql
  3. select sid,sname from student where sid in(select student_id from score where course_id in(select cid from course where teacher_id in (select tid from teacher where tname = '叶平')));
  • 查询没有学过全部课的学生 ```sql 先得到课程总数:select count(cname) from course) 再得到学过全部课程的学生:select student_id from score group by student_id having(count(course_id) in( select count(cname) from course)) 再从全部学生中排除学过全部课程的学生: select sid,sname from student where student.sid not in(select student_id from score group by student_id having(count(course_id) in( select count(cname) from course)));

```

复杂问题多进行拆分,然后in组装为一句(如果非写成一句的话就拆分-in)

不要通过查询得到的具体值去进行条件查询,因为数据是变化的!得用查询语句直接进行条件查询