SQL 加入,"there is an entry for table but it cannot be referenced"
SQL joins, "there is an entry for table but it cannot be referenced"
我有一个 SQL 查询失败,给我错误:
"There is an entry for table but it cannot be referenced from this part of the query"
通过查询,我需要所有 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 语句有关,但我不太明白是什么。我对这里发生的事情的解释非常感兴趣。
简单规则:永远不要在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 文档更好地描述了此语法的失败:
However, the precedence of the comma operator is less than of INNER
JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with
the other join types when there is a join condition, an error of the
form Unknown column 'col_name' in 'on clause' may occur. Information
about dealing with this problem is given later in this section.
我认为更简单的描述方式是 JOIN
是一个运算符,它作用于作为其参数的 tables/expressions。逗号分隔参数。因此,第一个 table 根本无法识别,因为逗号 "blocks" 它。
我认为您可以使用括号解决此问题:
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
但何必呢?查询的写法是正确的。
我有一个 SQL 查询失败,给我错误:
"There is an entry for table but it cannot be referenced from this part of the query"
通过查询,我需要所有 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 语句有关,但我不太明白是什么。我对这里发生的事情的解释非常感兴趣。
简单规则:永远不要在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 文档更好地描述了此语法的失败:
However, the precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form Unknown column 'col_name' in 'on clause' may occur. Information about dealing with this problem is given later in this section.
我认为更简单的描述方式是 JOIN
是一个运算符,它作用于作为其参数的 tables/expressions。逗号分隔参数。因此,第一个 table 根本无法识别,因为逗号 "blocks" 它。
我认为您可以使用括号解决此问题:
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
但何必呢?查询的写法是正确的。