如何在 SQL 中加入两个条件子查询?

How can I join two conditional subqueries in SQL?

我正在尝试在 PGAdmin (v1.20.0) 中加入两个子查询,如下所示:

SELECT * FROM (
    SELECT DISTINCT 
        course_code "400-Level Courses", 
        meet_time_start "Starting Time", 
        meet_time_end "End Time", 
        meet_day_of_week "Day", 
        building_code "Building", 
        building_room_no "Room" 
    FROM faculty_course_credit
    LEFT JOIN course_schedule USING (term_id, course_code, course_ref_no)
    WHERE (SUBSTRING(course_code, 4, 1) = '4') AND meet_time_start != '00:00'
) 
INNER JOIN (
    SELECT * FROM (
        SELECT DISTINCT 
            course_code "500-Level Courses", 
            meet_time_start "Starting Time", 
            meet_time_end "End Time", 
            meet_day_of_week "Day", 
            building_code "Building", 
            building_room_no "Room" 
        FROM faculty_course_credit 
        LEFT JOIN course_schedule USING (term_id, course_code, course_ref_no)
        WHERE (SUBSTRING(course_code, 4, 1) = '5') AND meet_time_start != '00:00'
    )
) 
USING (
    building_code=building_code, 
    building_room_no=building_room_no, 
    meet_time_start=meet_time_start, 
    meet_time_end=meet_time_end, 
    meet_day_of_week=meet_day_of_week
)

我没有在架构中创建表的权限,而且我不断收到以下错误消息:

ERROR:  subquery in FROM must have an alias
LINE 1:  select * from (
                       ^
HINT:  For example, FROM (SELECT ...) [AS] foo.
********** Error **********

ERROR: subquery in FROM must have an alias
SQL state: 42601
Hint: For example, FROM (SELECT ...) [AS] foo.
Character: 16

有什么建议吗?

错误说明了一切。每个子查询或派生 table 必须 有一个别名。它看起来像这样:

SELECT * FROM ( ... ) AS alias1 -- AS keyword is not needed, but I prefer it for readability

这是你遗漏的部分。


此外,如果您在要加入的两个派生 table 中有相似的名称,并且您使用的是 JOIN ... USING () 语法,那么正确的方法是:

SELECT t.col1, t.col2, t2.col1, t2.col2 -- this is to show you that names in both tables are identical
FROM table t
LEFT JOIN table2 t2 USING (col1, col2)

这意味着您不需要相等运算符。您仅在使用 JOIN ... ON 子句时指定相等条件,在上面的情况下看起来像:

SELECT t.*, t2.*
FROM table t
LEFT JOIN table2 t2 ON t.col1 = t2.col1 AND t.col2 = t2.col2

我注意到您正在重命名两个派生 table 中的列。在 JOIN 子句中,您需要指定可用于外部查询的名称。这些将是重命名的列名称,而不是它们的初始名称。