多表连接查询 (1) 查询选修了【数据库原理】的计算机系的学生学号和姓名。 (2) 查询每一门课的间接先行课(即先行课的先行课),显示课程编号和该门课程的间接先行课编号。 (3) 查询学生的学号、姓名、选修课程的名称和成绩。 (4) 查询选修了课程的学生姓名。 (5) 查询所有学生的信息和所选修的课程, 要求显示学生的学号、姓名、课程号及课程名。没有选课的同学对应的选课信息为空。 (6) 查询所有课程的课程编号、课程名称及选课人数,没有被选的课程选课人数显示为0。 (7) 列出所有学生所有可能的选修情况,要求显示学生的学号、姓名、课程号及课程名。 (8) 查找计算机系的学生选修课程数大于2 的学生的姓名、 平均成绩和选课门数,并按平均成绩降序排列。
时间: 2023-11-16 09:17:24 浏览: 152
数据库管理与应用 5.3.1使用内连接(INNER JOIN)进行多表查询.pdf
1.
```
SELECT s.id, s.name
FROM student s
JOIN course_selection cs ON s.id = cs.student_id
JOIN course c ON cs.course_id = c.id
WHERE s.department = '计算机系'
AND c.name = '数据库原理';
```
2.
```
WITH RECURSIVE prerequisites AS (
SELECT course_id, prerequisite_id
FROM prerequisite
UNION
SELECT p.course_id, pr.prerequisite_id
FROM prerequisites pr
JOIN prerequisite p ON pr.course_id = p.prerequisite_id
)
SELECT c.id, pr.prerequisite_id
FROM course c
LEFT JOIN prerequisites pr ON c.id = pr.course_id;
```
3.
```
SELECT s.id, s.name, c.name, cs.grade
FROM student s
JOIN course_selection cs ON s.id = cs.student_id
JOIN course c ON cs.course_id = c.id;
```
4.
```
SELECT s.name
FROM student s
JOIN course_selection cs ON s.id = cs.student_id;
```
5.
```
SELECT s.id, s.name, c.id, c.name
FROM student s
LEFT JOIN course_selection cs ON s.id = cs.student_id
LEFT JOIN course c ON cs.course_id = c.id;
```
6.
```
SELECT c.id, c.name, COUNT(cs.student_id) AS num_students
FROM course c
LEFT JOIN course_selection cs ON c.id = cs.course_id
GROUP BY c.id, c.name;
```
7.
```
SELECT s.id, s.name, c.id, c.name
FROM student s
CROSS JOIN course c;
```
8.
```
WITH course_counts AS (
SELECT s.id, s.name, COUNT(cs.course_id) AS num_courses
FROM student s
JOIN course_selection cs ON s.id = cs.student_id
WHERE s.department = '计算机系'
GROUP BY s.id, s.name
HAVING COUNT(cs.course_id) > 2
),
average_grades AS (
SELECT s.id, AVG(cs.grade) AS avg_grade
FROM student s
JOIN course_selection cs ON s.id = cs.student_id
GROUP BY s.id
)
SELECT cc.name, ag.avg_grade, cc.num_courses
FROM course_counts cc
JOIN average_grades ag ON cc.id = ag.id
ORDER BY ag.avg_grade DESC;
```
阅读全文