以下 PostgreSQL 查询有什么问题?
UPDATE project_project SET project_project.create_date = assignments.start_date
FROM project_project
LEFT JOIN account_analytic_account ON account_analytic_account.id = project_project.analytic_account_id
LEFT JOIN assignments ON assignments.accounts_ref = account_analytic_account.id
给出
[SQL] UPDATE project_project SET project_project.create_date = assignments.start_date
FROM project_project
LEFT JOIN account_analytic_account ON account_analytic_account.id = project_project.analytic_account_id
LEFT JOIN assignments ON assignments.accounts_ref = account_analytic_account.id
[Err] ERROR: table name "project_project" specified more than once
我试过了,
UPDATE pp SET pp.create_date = am.start_date
FROM project_project as pp
LEFT JOIN account_analytic_account as aa ON aa.id = pp.analytic_account_id
LEFT JOIN assignments as am ON am.accounts_ref = aa.id
给出
[SQL] UPDATE pp SET pp.create_date = am.start_date
FROM project_project pp
LEFT JOIN account_analytic_account aa ON aa.id = pp.analytic_account_id
LEFT JOIN am ON am.accounts_ref = aa.account_analytic_account.id
[Err] ERROR: relation "pp" does not exist
LINE 1: UPDATE pp SET pp.create_date = am.start_date
正确的语法是什么?
答案 0 :(得分:2)
要避免两个问题:
1-在SET列=值中,不要在column
前添加表名或别名。它产生错误并且无论如何都是无用的,因为UPDATE tablename
只能从tablename
更新列。 tablename的别名可以在其他地方使用,但不能在SET子句中使用。
2-不要在查询的其余部分重复要更新的表名,除非您要特别引发该表的二次和不相关扫描。
以下是我提出的修改后的查询建议,希望能满足您的要求:
UPDATE project_project pp SET create_date =
(select assignments.start_date FROM account_analytic_account LEFT JOIN assignments
ON assignments.accounts_ref = account_analytic_account.id
WHERE
account_analytic_account.id = pp.analytic_account_id);