Postgresql 用适当的联接替换子查询

Postgresql 用适当的联接替换子查询,postgresql,join,left-join,Postgresql,Join,Left Join,如何删除具有联接的子查询 SELECT distinct t."groupId" FROM "contacts" c INNER JOIN ( SELECT DISTINCT td.* FROM "groups" g INNER JOIN "territory" td ON td."gr

如何删除具有联接的子查询

SELECT distinct t."groupId" FROM "contacts" c 
        INNER JOIN
        ( 
        SELECT DISTINCT td.* FROM "groups" g
        INNER JOIN 
        "territory" td 
        ON 
        td."groupId" = g.id
        WHERE g."orgId" = 3
        ) 
        t
        ON 
        ST_Intersects(t.points, c."geoPoint")
        WHERE c.id = 33 and c."orgId" = 3

子查询没有问题,但是您应该摆脱可怕的
独特的

SELECT td."groupId"
FROM territory AS td
WHERE EXISTS (SELECT 1 FROM contacts AS c
              WHERE ST_Intersects(td.points, c."geoPoint")
                AND c.id = 33
                AND c."orgId" = 3)
  AND EXISTS (SELECT 1 FROM groups AS g
              WHERE td."groupId" = g.id
                AND g."orgId" = 3);
如果坚持不使用子查询,请使用

SELECT DISTINCT t."groupId"
   FROM contacts c 
      INNER JOIN territory td 
         ON ST_Intersects(td.points, c."geoPoint")
      INNER JOIN groups g
         ON td."groupId" = g.id
WHERE g."orgId" = 3
  AND c.id = 33
  AND c."orgId" = 3;

如果需要确保仅对来自
区域
且与
联接匹配的行调用
st_intersects
函数,则必须使用子查询。没有其他方法可以强制加入订单。

客户端根本不需要子查询。:/愚蠢的要求。我添加了一个替代方案。实际上,我只想在满足td.groupid=g.id连接的td(区域)上进行st_intersect,基本上使用第二次连接返回到st_intersect连接的区域,这就是您将得到的。我发布的查询正在工作,但这不是:/
无法生成外部点是错误。无论第二次连接如何,您的查询都会与每个区域相交