【问题标题】:SQL joins, "there is an entry for table but it cannot be referenced"SQL 连接,“表有条目但无法引用”
【发布时间】:2016-12-09 14:07:43
【问题描述】:

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

“有一个表条目,但不能从这部分查询中引用”

通过查询,我需要所有 3 个表,但只有trips 和boats 具有匹配的ID 才能加入。测试是一个 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 语句有关,但我不太明白是什么。我对这里发生的事情的解释非常感兴趣。

【问题讨论】:

  • 澄清一下——你是不是有意交叉加入tripstest
  • 不要混合隐式和显式连接,也不要在from 子句中添加逗号。
  • 用更传统的方式可能是... from trips join test on (st_intersects(trips.geom, test.geom)) join boats on (boats.id = trips.boat_id) where boats.uid = 44;
  • @Abelisto,谢谢。你能解释一下为什么吗?

标签: sql postgresql postgis


【解决方案1】:

简单规则:从不FROM 子句中使用逗号。 总是使用明确的JOIN 语法。 . .即使这意味着写出CROSS JOIN

如cmets中所说,查询的正确写法是:

 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 等等。如果您将逗号连接与 当存在连接条件时,其他连接类型的错误 可能会出现“on 子句”中的“未知列”“col_name”。信息 关于如何处理这个问题在本节后面给出。

我认为更简单的描述方式是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

但是为什么要麻烦呢?有一种编写查询的正确方法。

【讨论】:

  • 看起来这里提到的“正确方式”依赖于连接是一个布尔值。仅供参考。
猜你喜欢
  • 1970-01-01
  • 2017-12-04
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 2019-01-06
  • 2020-03-19
  • 2013-03-29
  • 1970-01-01
相关资源
最近更新 更多