简体   繁体   English

在Postgresql中连接多个表

[英]Joins on multiple tables in Postgresql

I'm practising for an upcoming database exam and I'm trying to get my head around nested and multiple joins in SQL, specifically the Postgresql syntax. 我正在练习即将进行的数据库考试,我正试图了解SQL中的嵌套和多个连接,特别是Postgresql语法。 I want to return all the student names and department names of all students that achieved grade A. 我想要返回所有达到A级学生的学生姓名和部门名称。

Here's my schema. 这是我的架构。

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
);

I put together a nested statement that I thought would work: 我把一个我认为可行的嵌套语句放在一起:

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';

However, this gives me the error invalid reference to FROM-clause entry for table "t1" . 但是,这给了我invalid reference to FROM-clause entry for table "t1"的错误invalid reference to FROM-clause entry for table "t1" I'm guessing it is because that is not how you are supposed to name/reference JOINS. 我猜这是因为你不应该如何命名/引用JOINS。 I would like a way to JOIN all of these tables together. 我想要一种方法将所有这些表连接在一起。 Thanks! 谢谢!

Remove the parentheses and fix the aliases: 删除括号并修复别名:

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';

The parentheses are allowed, but they are not needed. 允许使用括号,但不需要它们。 When using parentheses (which is very, very rarely needed), they do not get separate aliases. 当使用括号(非常非常需要)时,它们不会获得单独的别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM