使用行内或链接 table 中字段的最旧记录更新时间戳字段

Update Timestamp field with the oldest record of fields within the row or those in a linked table

一个 table 看起来像这样:

TABLE A Nullables
a_id not nullable
create_timestamp not nullable
edit_timestamp nullable
closed_timestamp nullable
last_mod_timestamp not nullable

另一个是这样的:

TABLE B Nullables
b_id not nullable
table_a_fk not nullable
create_timestamp not nullable

如何将 last_mod_timestamp 设置为 (a.create_timestamp、a.edit_timestamp、a.closed_timestamp) 或 b.create_timestamp 中最旧的值,其中 b.table_a_fk = a.id?

数据类型都是时间戳。

提前致谢!

试试这个:

UPDATE TABLE_A A
SET 
  last_mod_timestamp =
NULLIF
(
  MAX 
  (
    COALESCE (A.create_timestamp, '0001-01-01'::TIMESTAMP)
  , COALESCE (A.edit_timestamp, '0001-01-01'::TIMESTAMP)
  , COALESCE (A.closed_timestamp, '0001-01-01'::TIMESTAMP)
  , COALESCE (B.create_timestamp, '0001-01-01'::TIMESTAMP)
  )
, '0001-01-01'::TIMESTAMP
)
FROM
(
  SELECT table_a_fk, MAX (create_timestamp) create_timestamp
  FROM TABLE_B
  GROUP BY table_a_fk
) B
WHERE A.a_id = B.table_a_fk