如何在SQL中连接两个条件子查询?

时间:2016-04-01 22:40:02

标签: sql join subquery

我试图在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)

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

  

错误:FROM中的子查询必须有一个别名LINE 1:select * from(                          ^提示:例如,FROM(SELECT ...)[AS] foo。   **********错误**********

     

错误:FROM中的子查询必须具有别名SQL状态:42601提示:For   例如,FROM(SELECT ...)[AS] foo。性格:16

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

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

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

这是你错过的部分。

此外,如果您要加入的两个派生表中都有类似的名称,并且您使用的是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

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