postgres查询显示错误

时间:2018-03-02 05:00:53

标签: sql postgresql

下面是我在同一个表本身上进行内连接的postgres查询。但是下面的查询在内连接之前显示错误。

select org.id, org.name, org.lft, org.rgt, tmp.id, tmp.name, tmp.lft, tmp.rgt from organization_organization as org WHERE (org.id IN (62)) 
INNER JOIN organization_organization as tmp ON (org.tree_id=tmp.tree_id) 
WHERE (tmp.id = org.id) OR (org.lft > tmp.lft AND org.rgt < tmp.rgt)

3 个答案:

答案 0 :(得分:2)

你的Join语法不正确,你的代码有两个where子句。在内部加入你的查询多次返回同一行,如果有任何列值重复,为了避免这种重复,你必须使用DISTINCT。

select 
    distinct on(org.id)
    org.id, 
    org.name, 
    org.lft, 
    org.rgt, 
    tmp.id, 
    tmp.name, 
    tmp.lft, 
    tmp.rgt 
from 
    organization_organization as org 
INNER JOIN 
    organization_organization as tmp 
ON 
    org.tree_id=tmp.tree_id
WHERE 
    org.id IN (62)
and
    (
        tmp.id = org.id
OR 
        org.lft > tmp.lft AND org.rgt < tmp.rgt
    )
group by org.id

答案 1 :(得分:1)

因为您的JOIN语法不正确。 INNER JOIN关键字出现在WHERE子句

之前
SELECT  org.id, 
        org.name, 
        org.lft, 
        org.rgt, 
        tmp.id, 
        tmp.name, 
        tmp.lft, 
        tmp.rgt 
FROM    organization_organization AS org 
        INNER JOIN organization_organization AS tmp 
            ON org.tree_id = tmp.tree_id
WHERE   org.id IN (62)
        AND 
        (
            (tmp.id = org.id) 
            OR (org.lft > tmp.lft AND org.rgt < tmp.rgt)
        )

答案 2 :(得分:0)

放置&#39; WHERE(org.id IN(62))&#39;在第二个WHERE子句

select org.id, org.name, org.lft, org.rgt, tmp.id, tmp.name, tmp.lft, 
tmp.rgt from organization_organization as org 
INNER JOIN organization_organization as tmp ON (org.tree_id=tmp.tree_id) 
WHERE ((tmp.id = org.id) OR (org.lft > tmp.lft AND org.rgt < tmp.rgt))
and (org.id IN (62))