案例:Student 学生表:(stuId[学号],stuName[学生姓名],stuAge[学生年龄],stuSex[学生性别]) Course 课程表:(courseld[课程编号],courseName[课程名字],teacherId[老师id]) Scores 成绩表:(stuId[学号],courseId[课程编号],score[成绩])
1.查询获得每门课程的最高成绩的学生姓名、成绩
sql语句:
SELECT student.`stuName`,scores.score,course.courseName
FROM student,course,scores WHERE student.`stuId`=scores.stuId
AND course.`courseld`=scores.`courseId` AND scores.`score` IN(SELECT
MAX(`score`) FROM scores GROUP BY `courseId`)
思路:使用子查询
优先解决分组问题得到最大学生编号,在联合查询条件是学生编号匹配。
2.查询没有选课程编号为2的学生姓名
sql语句:
SELECT ss.`stuName` FROM student ss,scores dd WHERE ss.`stuId`=dd.`stuId`
AND ss.`stuId` NOT IN (SELECT scores.`stuId` FROM scores WHERE scores.`courseId`=2)
3.查询选了所有课的同学的学号、姓名
sql语句: SELECT student.`stuId`,student.`stuName` FROM student WHERE student.`stuId` IN
(SELECT scores.`stuId` FROM scores GROUP BY scores.`stuId` HAVING (COUNT(scores.`courseId`) = (SELECT COUNT(courseld) AS t2 FROM course)))