34

我有以下 SQL (PostgreSQL) 查询:

SELECT ff.*, fp.*
FROM fibra ff, fibra fp

JOIN cables cp ON fp.cable_id = cp.id
LEFT OUTER JOIN terceiro  ced_pai ON ced_pai.id = cp.cedente_id
LEFT OUTER JOIN terceiro tp ON tp.id = fp.terceiro_id

JOIN cables cf ON ff.cable_id = cf.id
LEFT OUTER JOIN terceiro ced_f ON ced_f.id = cf.cedente_id
LEFT OUTER JOIN terceiro tf ON tf.id = ff.terceiro_id

where ff.fibra_pai_id = fp.id 
AND ff.cable_id IN (8,9,10) 
AND fp.cable_id IN (8,9,10)

但它给了我这个错误:

ERROR:  invalid reference to FROM-clause entry for table "ff"
LINE 8:  JOIN cables cf ON ff.cable_id = cf.id
           ^
HINT:  There is an entry for table "ff", but it cannot be referenced from this part of the query.

********** Error **********

ERROR: invalid reference to FROM-clause entry for table "ff"
SQL state: 42P01
Hint: There is an entry for table "ff", but it cannot be referenced from this part of the query.
Character: 261

有谁知道我做错了什么?

4

3 回答 3

41

您正在混合隐式和显式 JOIN。正如您刚刚发现的那样,这通常会令人困惑,并会导致意想不到的评估顺序问题。

您应该始终如一地JOIN ... ON在任何地方使用语法;避免遗留FROM table1, table2。如果您更正查询以使用显式 JOIN 而不是FROM fibra ff, fibra fp, 例如并从子句中FROM fibra ff INNER JOIN fibra fp ON (ff.fibra_pai_id = fp.id)省略,您应该得到预期的结果。ff.fibra_pai_id = fp.idWHERE

请参阅 AH 链接到的这个问题:

Mixing explicit and implicit joins fails with "There is an entry for table ... but it cannot be referenced from this part of the query"

于 2012-11-09T00:53:42.867 回答
2

将查询中的所有联接转换为显式,以避免您遇到的问题——不要留下一些隐含的和其他显式的。

这应该有效:

SELECT ff.*, fp.*
  FROM fibra ff

  JOIN fibra fp ON ff.fibra_pai_id = fp.id 

  JOIN cables cp ON fp.cable_id = cp.id
  LEFT OUTER JOIN terceiro  ced_pai ON ced_pai.id = cp.cedente_id
  LEFT OUTER JOIN terceiro tp ON tp.id = fp.terceiro_id

  JOIN cables cf ON ff.cable_id = cf.id
  LEFT OUTER JOIN terceiro ced_f ON ced_f.id = cf.cedente_id
  LEFT OUTER JOIN terceiro tf ON tf.id = ff.terceiro_id

WHERE
 ff.cable_id IN (8,9,10) 
 AND fp.cable_id IN (8,9,10)
于 2012-11-08T20:49:37.413 回答
0

In my case the problem was that I forgot I had assigned my tables to a particular schema and needed to reference those e.g:

select r.*
from my_schema.resources r
于 2021-08-25T16:08:00.703 回答