仅针对新行添加带有默认NOW()的时间戳列 [英] Add timestamp column with default NOW() for new rows only
问题描述
我有一个包含数千行的表。由于该表最初不是使用created_at列构建的,因此无法获取其创建时间戳。不过,开始获取未来行的时间戳至关重要。
I have a table that has thousands of rows. Since the table wasn't constructed with created_at column initially, there is no way of getting their creation timestamp. It is crucial though to start getting the timestamps for future rows.
有没有一种方法可以添加带有默认值NOW()的时间戳列,这样它就不会将值填充到先前的行中,而只会填充将来的行?
Is there a way I can add a timestamp column with default value NOW() so that it won't populate the values to previous rows but only for the future ones?
如果我执行 ALTER
查询,它将使用时间戳填充所有行:
If I do the ALTER
query, it populates all rows with timestamp:
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
推荐答案
您需要添加默认值为 null
的列,然后将其更改为默认值 now()
。
You need to add the column with a default of null
, then alter the column to have default now()
.
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();
这篇关于仅针对新行添加带有默认NOW()的时间戳列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!