我已经从mysql迁移到psql,但是发现使用多个左连接很难理解UPDATE语句。
你将如何在Postgres中重写?(我正在使用PostResql9.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;

欢迎任何指针。

最佳答案

干得好:

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

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

10-07 12:39
查看更多