Postgres:缺少表的FROM子句条目

时间:2017-09-18 08:37:20

标签: sql postgresql

我正在尝试在postgres上为4个表执行连接查询。

表名:

  • scenarios_scenario
  • payments_invoice
  • payments_payment
  • payments_action

(所有这些奇怪的名字都是由django生成的 - )))

关系:

  • scenarios_scenario [有很多] payments_action s
  • payments_action [有一个] payments_invoice
  • payments_action [有一个] payments_payment

下面是一个有效的查询,

SELECT payments_invoice.*,
    (payments_payment.to_be_paid - payments_payment.paid) as remaining, \
    payments_action.identificator
FROM payments_invoice
JOIN payments_payment
  ON payments_invoice.action_id = payments_payment.action_id
  AND payments_payment.full_payment=2
JOIN payments_action
  ON payments_invoice.action_id = payments_action.id
  AND payments_action.identificator = %s

我只是想从另一个表中检索相关字段并编写另一个查询,如

SELECT 
  scenarios_scenario.title, payments_invoice.*, \
  (payments_payment.to_be_paid - payments_payment.paid) as remaining, \
  payments_action.identificator, payments_action.scenario_id 
FROM payments_invoice 
JOIN scenarios_scenario 
  ON scenarios_scenario.id = payments_action.scenario_id
JOIN payments_payment 
  ON payments_invoice.action_id = payments_payment.action_id 
  AND payments_payment.full_payment=2 
JOIN payments_action 
  ON payments_invoice.action_id = payments_action.id 
  AND payments_action.identificator = 'EEE45667';

但面临此错误 -

ERROR:  missing FROM-clause entry for table "payments_action"
LINE 2: ...IN  scenarios_scenario ON scenarios_scenario.id = payments_a...
                                                             ^

在SO中查找类似的问题(missing FROM-clause entry for table),但无法找到方法。任何帮助,将不胜感激。

3 个答案:

答案 0 :(得分:7)

在您的第一次加入中,“payments_action”不是已知关系。以新连接仅使用已经“定义”关系的方式重新排序连接。

这是一个小提琴,展示了这个问题:

http://sqlfiddle.com/#!17/ed147/5

答案 1 :(得分:4)

更改代码,以便在从另一个联接中调用其中的列之前加入每个表。 postgres查询计划程序按顺序读取连接,以便在您的代码表scenarios_scenario中加入表payments_invoice并正在寻找与payments_action的匹配,但查询计划程序不会知道payments_action到底是什么。新代码应该是:

SELECT 
    scenarios_scenario.title, payments_invoice.*, \
    (payments_payment.to_be_paid - payments_payment.paid) as remaining, \
    payments_action.identificator, payments_action.scenario_id 
FROM payments_invoice 
JOIN payments_action 
ON (
    payments_invoice.action_id = payments_action.id 
    AND payments_action.identificator = 'EEE45667'    
)
JOIN scenarios_scenario 
ON (
    scenarios_scenario.id = payments_action.scenario_id
)
JOIN payments_payment 
ON (
    payments_invoice.action_id = payments_payment.action_id 
    AND payments_payment.full_payment=2 
);

答案 2 :(得分:3)

您正使用[payments_action]中的字段加入表[scenario_scenario]。

连接必须按顺序连接,即除非它们的表位于语句之前,否则不能使用ON语句引用表中的字段。

希望有所帮助