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

lcg*_*ida 22 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)
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

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
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么?

Cra*_*ger 30

您正在混合隐式和显式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链接到的这个问题:

混合显式和隐式连接失败,"有一个表的条目......但是它不能从查询的这一部分引用"

  • @AlexisWilke`FROM`在某种意义上当然不是"遗产".非ansi连接语法`FROM table1,table2 WHERE tablea.id = tableb.id`通常被认为是,而ANSI内连接则更受青睐.如果你想要一个未经过滤的笛卡尔积,你可以使用`tablea CROSS JOIN tableb`,让你的意图明确. (6认同)
  • **传统**`FROM`?真的吗?它用于计算 _Cartesian Product_ 并且您甚至需要它来使用`INNER JOIN`,不是吗?http://www.postgresql.org/docs/9.3/static/sql-select.html#SQL-FROM (2认同)