我有一个projects
表,其中包含时间戳列started_at
和tasks
表,其中包含project_id
和started_at
列。
有没有办法使用单个查询进行批量更新,projects
行设置started_at
started_at
表中最早的tasks
值?
例如,如果表tasks
包含行:
project_id | started_at
1 | 2010-01-01
1 | 2015-01-01
2 | 2000-01-01
2 | 2020-01-01
运行查询会像这样更新projects
表
id | started_at
1 | 2010-01-01
2 | 2000-01-01
我使用PostgreSQL。
答案 0 :(得分:1)
UPDATE projects
SET started_at = OldestDate
FROM
(
SELECT project_id, MIN(started_at) AS OldestDate
FROM tasks
GROUP BY project_id
) AS t
WHERE t.project_id = id;