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

我正在将一些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, ... 

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

最佳答案
我不知道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

转载注明原文:sql – 在多个表上执行左连接时遇到问题 - 代码日志