使用LEFT JOIN和ON子句时如何解决WHEREerror

时间:2018-12-27 19:55:09

标签: postgresql

我花了至少4个小时来解决它,我尝试了很多发布在这里的解决方案,但是我仍然没有解决它。

这是我的查询

SELECT * FROM l_article 
         INNER JOIN accounts_user 
         LEFT JOIN laws_marcacao ON (laws_marcacao.article_id = l_article.id 
                                AND laws_marcacao.user_id = accounts_user.id) 
         WHERE l_article.law_id = 1 and accounts_user.id = 1

where附近发生错误:

ERROR:  syntax error at or near "where"
LINE 5:                        where l_article.law_id = 1 and accoun...
                               ^

2 个答案:

答案 0 :(得分:1)

问题是l_article和accounts_user之间的内部联接,它缺少合格的联接。

语法:

T1 { [INNER] | { LEFT | RIGHT | FULL } [OUTER] } JOIN T2 ON boolean_expression
T1 { [INNER] | { LEFT | RIGHT | FULL } [OUTER] } JOIN T2 USING ( join column list )
T1 NATURAL { [INNER] | { LEFT | RIGHT | FULL } [OUTER] } JOIN T2

https://www.postgresql.org/docs/9.2/queries-table-expressions.html

因此,如果要执行笛卡尔乘积,则使用CROSS JOIN而不是INNER JOIN。如果要使用INNER JOIN,则需要具有连接条件,例如USING或ON子句。

查看此sqlfiddle

答案 1 :(得分:1)

使联结表脱离最终结果的简单技巧:


SELECT * 
FROM l_article a
JOIN accounts_user u ON EXISTS (
        SELECT * 
        FROM laws_marcacao xx
        WHERE xx.article_id = a.id                        
        AND xx.user_id = u.id
        )
WHERE a.law_id = 1 AND u.id = 1
  ;