错误:对FROM子句的无效引用

时间:2012-11-08 20:43:11

标签: postgresql join

我有以下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

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:26)

您正在混合隐式和显式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.id子句中省略WHERE,则应获得预期结果。

请参阅A.H.链接到的问题:

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

答案 1 :(得分:1)

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

这应该有效:

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)