在多个表上执行左连接时遇到问题

时间:2012-07-24 17:39:30

标签: sql postgresql syntax-error

我正在将一些mysql查询转移到postgres,我遇到了一个无法运行的问题。

select (tons of stuff)
from trip_publication 

left join trip_collection AS "tc" on
tc.id = tp.collection_id

left join 
            trip_author ta1, (dies here)
            trip_person tp1,
            trip_institution tai1,
            trip_location tail1,
            trip_rank tr1
    ON
            tp.id = ta1.publication_id 
            AND tp1.id = ta1.person_id 
            AND ta1.order = 1 
            AND tai1.id = ta1.institution_id 
            AND tail1.id = tai1.location_id 
            AND ta1.rank_id = tr1.id

查询似乎在“trip_author ta1”行上死亡,我在上面标记了它。实际的错误消息是:

   syntax error at or near ","
   LINE 77:   (trip_author ta1, trip_person tp1, ... 

我浏览了文档,似乎是正确的。我到底错在了什么?任何反馈都会非常感激。

2 个答案:

答案 0 :(得分:8)

我不知道postgres,但在常规SQL中,您需要一系列LEFT JOIN语句而不是逗号语法。你似乎已经开始了这个,然后在前两个之后停止了。

类似的东西:

SELECT * FROM
table1 
LEFT JOIN table2 ON match1
LEFT JOIN table3 ON match2
WHERE otherFilters

替代方法是旧的SQL语法:

SELECT cols
FROM table1, table2, table3
WHERE match AND match2 AND otherFilters

您的SQL中还有一些其他较小的错误,例如您在第一个表上忘记了tp别名,并尝试包含where子句(ta1.order = 1)加入约束。

我认为这就是你所追求的目标:

select (tons of stuff)
from trip_publication tp 
left join trip_collection AS "tc" on tc.id = tp.collection_id
left join trip_author ta1 on ta1.publication_id  = tp.id
left join trip_person tp1 on tp1.id = ta1.person_id 
left join trip_institution tai1 on  tai1.id = ta1.institution_id 
left join trip_location tail1 on tail1.id = tai1.location_id 
left join trip_rank tr1 on tr1.id = ta1.rank_id
where ta1.order = 1

答案 1 :(得分:1)

您的左连接是每个要加入的桌子的连接

左加入trip_author ta1 .... 离开加入trip_person tp1 .... 离开加入trip_institution ......

......等等

相关问题