Postgres UPDATE语句

时间:2015-04-14 11:51:22

标签: postgresql sql-update postgresql-9.4

我已经从mysql迁移到了psql,但发现很难使用多个左连接来了解UPDATE语句。

你会如何在Postgres中重写这个? (我正在使用postresql 9.4)

update task t 
    left join project p on t.project_id = p.id 
    left join client c on t.client_id = c.id 
    left join user u on t.user_id = u.id
set t.project_name = p.name, 
     t.client_name = c.name,
     t.user_name = u.name;

欢迎使用任何指针。

1 个答案:

答案 0 :(得分:0)

你走了:

WITH task_data AS (
    SELECT t.id,
        p.name AS project_name,
        c.name AS client_name,
        u.name AS user_name
    FROM task t 
        LEFT JOIN project p ON t.project_id = p.id 
        LEFT JOIN client c ON t.client_id = c.id 
        LEFT JOIN "user" u ON t.user_id = u.id
)
UPDATE task t
FROM task_data d
SET
    project_name = d.project_name, 
    client_name = d.client_name,
    user_name = d.user_name
WHERE t.id = d.id

我很想知道是否有更有效的方式