简体   繁体   中英

How to copy column from one table to another using JOIN

What is wrong with the following PostgreSQL query?

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

gives

[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

I tried,

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

gives

[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  

What is the correct syntax?

There are two problems to avoid:

1- in SET column=value, do not prepend a table name or alias to column . It yields an error and is useless anyway, since UPDATE tablename is only able to update columns from tablename . An alias of tablename can be used in other places, but not in the SET clause.

2- don't repeat the name of the table to update in the rest of the query unless you want to specifically induce a secondary and uncorrelated scan of this table.

Here is my proposal of a modified query that I hope does what you intend:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM