mysql数据库查询的习题和答案
时间: 2023-09-23 07:05:04 浏览: 105
以下是一些MySQL数据库查询练习题及其答案:
1. 查询所有学生的姓名和年龄。
```
SELECT name, age FROM students;
```
2. 查询所有科目的名称和学分。
```
SELECT subject_name, credits FROM subjects;
```
3. 查询所有学生的姓名和所在班级的名称。
```
SELECT students.name, classes.class_name
FROM students
JOIN classes ON students.class_id = classes.class_id;
```
4. 查询所有选修了“数据库”课程的学生的姓名和所在班级的名称。
```
SELECT students.name, classes.class_name
FROM students
JOIN classes ON students.class_id = classes.class_id
JOIN enrollments ON students.student_id = enrollments.student_id
JOIN courses ON enrollments.course_id = courses.course_id
WHERE courses.course_name = "数据库";
```
5. 查询所有学生的姓名和选修的所有课程的名称。
```
SELECT students.name, GROUP_CONCAT(courses.course_name SEPARATOR ',') AS courses_taken
FROM students
JOIN enrollments ON students.student_id = enrollments.student_id
JOIN courses ON enrollments.course_id = courses.course_id
GROUP BY students.student_id;
```
6. 查询所有学生的姓名和选修课程的总学分数。
```
SELECT students.name, SUM(subjects.credits) AS total_credits
FROM students
JOIN enrollments ON students.student_id = enrollments.student_id
JOIN courses ON enrollments.course_id = courses.course_id
JOIN subjects ON courses.subject_id = subjects.subject_id
GROUP BY students.student_id;
```
7. 查询所有学生的姓名和平均成绩(假设每个学生的每个课程只有一次考试)。
```
SELECT students.name, AVG(grades.grade) AS average_grade
FROM students
JOIN enrollments ON students.student_id = enrollments.student_id
JOIN courses ON enrollments.course_id = courses.course_id
JOIN grades ON enrollments.enrollment_id = grades.enrollment_id
GROUP BY students.student_id;
```
以上是一些较为基础的MySQL数据库查询练习题及其答案,希望对你有所帮助!
阅读全文