查询“C001”课程成绩比“C002”课程成绩高的学生姓名、课程名、“计算机导论”课程成绩,多表查询
时间: 2023-11-05 12:08:27 浏览: 109
假设有以下三个表:
学生表(student):
| id | name |
| ---- | ------- |
| 1 | 小明 |
| 2 | 小红 |
| 3 | 小刚 |
| 4 | 小李 |
课程表(course):
| id | name |
| ---- | ---------- |
| C001 | 计算机导论 |
| C002 | 数据结构 |
成绩表(score):
| id | student_id | course_id | score |
| ---- | ----------| ---------| ------|
| 1 | 1 | C001 | 85 |
| 2 | 1 | C002 | 76 |
| 3 | 2 | C001 | 92 |
| 4 | 2 | C002 | 88 |
| 5 | 3 | C001 | 80 |
| 6 | 3 | C002 | 82 |
| 7 | 4 | C001 | 78 |
| 8 | 4 | C002 | 90 |
可以使用以下 SQL 语句实现查询:
```
SELECT s.name AS student_name, c.name AS course_name, s1.score AS score
FROM score s1
JOIN student s ON s.id = s1.student_id
JOIN course c ON c.id = s1.course_id
JOIN (SELECT student_id, score FROM score WHERE course_id = 'C001') s2 ON s2.student_id = s1.student_id
WHERE s1.course_id = 'C002' AND s1.score < s2.score;
```
以上 SQL 语句中,第一个 JOIN 子句将成绩表(score)与学生表(student)连接,第二个 JOIN 子句将成绩表(score)与课程表(course)连接,第三个 JOIN 子句将成绩表(score)自连接,获取“C001”课程的成绩,然后通过 WHERE 子句筛选出“C002”课程成绩比“C001”课程成绩高的学生,并输出学生姓名、课程名、“计算机导论”课程成绩。
阅读全文