数据库MySQL查询学生的学号、姓名、选修课程的课程名及成绩。(3表连接)
时间: 2023-06-17 19:06:18 浏览: 287
mysql 查询语句学生表、课程表、 成绩表、教师表.docx
假设我们有三张表:`students`、`courses`和`scores`,分别存储学生信息、课程信息和成绩信息。它们的结构如下:
```
students表:
+----+--------+
| id | name |
+----+--------+
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie|
+----+--------+
courses表:
+----+-----------+
| id | name |
+----+-----------+
| 1 | Math |
| 2 | Physics |
| 3 | Chemistry |
+----+-----------+
scores表:
+----+------------+--------+-------+
| id | student_id | course_id | score |
+----+------------+----------+-------+
| 1 | 1 | 1 | 90 |
| 2 | 1 | 2 | 85 |
| 3 | 2 | 1 | 95 |
| 4 | 2 | 3 | 80 |
| 5 | 3 | 2 | 92 |
| 6 | 3 | 3 | 88 |
+----+------------+----------+-------+
```
我们可以通过以下 SQL 语句查询学生的学号、姓名、选修课程的课程名及成绩:
```
SELECT students.id, students.name, courses.name, scores.score
FROM students
INNER JOIN scores ON students.id = scores.student_id
INNER JOIN courses ON scores.course_id = courses.id;
```
运行结果如下:
```
+----+--------+-----------+-------+
| id | name | name | score |
+----+--------+-----------+-------+
| 1 | Alice | Math | 90 |
| 1 | Alice | Physics | 85 |
| 2 | Bob | Math | 95 |
| 2 | Bob | Chemistry | 80 |
| 3 | Charlie| Physics | 92 |
| 3 | Charlie| Chemistry | 88 |
+----+--------+-----------+-------+
```
阅读全文