我正在为即将到来的数据库考试做练习,并且试图使嵌套和SQL中的多个联接(尤其是Postgresql语法)更加深入人心。我想返回所有获得A级成绩的学生的所有学生姓名和部门名称。
这是我的模式。
CREATE TABLE student1 (
student_number INTEGER NOT NULL PRIMARY KEY,
name TEXT NOT NULL,
class INTEGER NOT NULL,
major TEXT NOT NULL
);
CREATE TABLE course1 (
course_name TEXT NOT NULL,
course_number TEXT NOT NULL PRIMARY KEY,
credit_hours INTEGER NOT NULL,
department TEXT NOT NULL
);
CREATE TABLE section1 (
section_identifer INTEGER NOT NULL PRIMARY KEY,
course_number TEXT NOT NULL,
semester TEXT NOT NULL,
year INTEGER NOT NULL,
instructor TEXT NOT NULL,
FOREIGN KEY (course_number) REFERENCES course1(course_number) ON DELETE CASCADE
);
CREATE TABLE grade_report1 (
id SERIAL NOT NULL PRIMARY KEY,
student_number INTEGER NOT NULL,
section_identifer INTEGER NOT NULL,
grade TEXT NOT NULL,
FOREIGN KEY (student_number) REFERENCES student1(student_number) ON DELETE CASCADE,
FOREIGN KEY (section_identifer) REFERENCES section1(section_identifer) ON DELETE CASCADE
);
我整理了一个我认为行得通的嵌套语句:
SELECT t1.name, t3.department
FROM (student1 t1 INNER JOIN grade_report1 t2 ON t1.student_number = t2.student_number) t5
INNER JOIN (course1 t3 INNER JOIN section1 t4 ON t3.course_number = t4.course_number) t6
ON t5.section_identifer = t6.section_identifer
WHERE t2.grade = 'A';
但是,这给了我错误invalid reference to FROM-clause entry for table "t1"
。我猜是因为那不是您应该如何命名/引用JOINS的方式。我想要一种将所有这些表联接在一起的方法。谢谢!
答案 0 :(得分:0)
删除括号并修复别名:
SELECT s.name, c.department
FROM student1 s INNER JOIN
grade_report1 gr
ON gr.student_number = s.student_number INNER JOIN
section1 sec
ON sec.section_identifer = gr.section_identifer INNER JOIN
course1 c
ON sec.course_number = c.course_number
WHERE gr.grade = 'A';
允许使用括号,但不需要。使用括号(非常非常需要)时,它们不会获得单独的别名。