首页 > 解决方案 > 从列中提取年份并更新另一列 PostgreSQL

问题描述

我在表中创建了另一列,我想通过提取年份从同一表列 tdate 填充它,有人可以告诉我该怎么做吗?

从 test_tb 中选择 EXTRACT (YEAR from tdate),但是我现在如何为每一行分配值?

tdate                        year
2006-01-02 00:00:01.132000   null
2007-01-02 00:00:01.234000   null  
2008-01-02 00:00:01.336000   null
2009-01-02 00:00:01.538000   null
2010-01-02 00:00:01.639000   null
2011-01-02 00:00:03.107000   null
2012-01-02 00:00:03.210000   null
2013-01-02 00:00:03.261000   null
2014-01-02 00:00:03.363000   null
2015-01-02 00:00:03.465000   null
2016-01-02 00:00:03.591000   null
2017-01-02 00:00:04.475000   null
2018-01-02 00:00:04.526000   null
2019-01-02 00:00:04.629000   null
2020-01-02 00:00:04.731000   null

谢谢!

标签: postgresql

解决方案


这是一个坏主意。您始终可以在 Select 上提取年份。当日期更新但年份列没有更新时会发生什么。如果您必须存储它并使用 Postgres 12(或更高版本),请考虑将其创建为生成的列。所以

alter table add column year integer generated always as (extract (year from tdate)) stored;

这避免了更新问题上面的问题。
警告:年份并不是一个好的列名。虽然不是 Postgres保留字,但它是 SQL 标准保留字。这可能会导致将来出现意外错误。


推荐阅读