SQL连接,“有一个表的条目,但它不能被引用”

时间:2016-08-03 17:55:49

标签: sql postgresql postgis

我有一个失败的SQL查询,给我错误:

  

“表格中有一个条目,但无法从查询的这一部分引用”

通过查询,我需要所有3个表,但只有旅行和船只有匹配的ID才能加入。 Test是一个shapefile,我需要执行一个postGIS函数,但它与其他两个没有相似的列id。

 select trips.*
 from trips, test
 inner join boats on boats.id = trips.boat_id
 where st_intersects(trips.geom, test.geom) and
 boats.uid = 44

我认为它与join语句有关,但我真的不明白。我对这里发生的事情的解释非常感兴趣。

1 个答案:

答案 0 :(得分:5)

简单规则:从不FROM子句中使用逗号。 始终使用显式JOIN语法。 。 。即使这意味着写出CROSS JOIN

正如评论中所提到的,编写查询的正确方法是:

 select trips.*
 from trips inner join
      test
      on st_intersects(trips.geom, test.geom) inner join
      boats
      on boats.id = trips.boat_id
 where boats.uid = 44;

然而,问题是为什么这不起作用:

from trips,
     test inner join
     boats
     on boats.id = trips.boat_id

首先,我想指出,在MySQL documentation中比在Postgres文档中更好地描述了这种语法的失败:

  

但是,逗号运算符的优先级小于INNER   JOIN,CROSS JOIN,LEFT JOIN等等。如果你混合使用逗号连接   当有连接条件时,其他连接类型,错误   表格未知栏' col_name'在' on条款'可能导致。信息   关于这个问题的处理将在本节后面给出。

我认为更简单的描述方式是JOIN是一个操作符,它作用于作为其参数的表/表达式。逗号分隔参数。因此,第一个表格根本没有被识别,因为逗号"阻止"它

我认为你可以使用括号来解决这个问题:

from (trips, test inner) join
     boats
     on boats.id = trips.boat_id

你绝对可以使用CROSS JOIN来解决这个问题:

from trips cross join
     test inner join
     boats
     on boats.id = trips.boat_id

但为什么要这么麻烦?有一种正确的方式来编写查询。