看下 面试题 感觉难倒我了。

写下SQL语句,查出至少学2门课程的且分数都至少80分的学生,难倒我了。。
两张表
Stu表:

sid(学生编号),
name(学生姓名)

Grade表:
gid(年级表编号),
cid(课程编号),
sid(学生表外键),
grade(课程分数)

    select s.* 
    from Stu s, Grade g
    where s.sid = g.sid and g.grade >= 80
    group by s.sid
    having count(s.sid) >=2;

“查出至少学2门课程的且分数都至少80分的学生”这句话有歧义,可以理解为下面两个意思:
1)至少选了两门课,并且至少两门课不低于80分的学生;
2)至少选了两门课,每门课都不低于80分的学生;
从实际考虑,我觉得愿意思应该是1) ,SQL也是按1)的意思写的。如果是2)的话 sql要调整

这个表建立有问题。学生表和年级表,是多对一。就是多个学生对应一个年级,外键应该放在学生表中,在年级表中不能存在学生表的外键。设计问题,如果非要查的话
select * from Stu where sid = (
select sid (
select sid count(id) as gcount from Grade where count>80 and g.sid in (
_select sid from (
select count(id) as scount from Grade group by sid) n
where n.scount>=2)
//选课大于2的SID
) )y.gcount>2_ //成绩都大于80的
)
别纠结这个了。

  1. 拿到超过80分的课程数量 select * from Grade where grade >= 80
  2. 根据学生id分组拿到高于80分的每个学生选的课程数量 select count(cid) as selectedCourse ,sid from ( select * from Grade where grade >= 80 ) group by sid
  3. 学生和统计数据连接,取值最后得到学生的信息 select Stu.sid,name from Stu as table1,
    (select count(cid) as selectedCourse,sid from ( select * from Grade where grade >= 80 ) group by sid) as table2 where table1.sid = table2.sid and table2.sid.selectedCourse > 2

select * from Stu wher sid in(select sid from (select sid,count(cid) from Grade where grade>80) group up sid having count(cid)>2);

SELECT DISTINCT*from Stu where sid in(select sid from grade group by sid having count(grade>=80)>=2)这是查询选修了至少两门课且至少两门课都不少于80分的学生信息

感谢各位,已经是2015年的问答了,才发现。谢谢你们