postgresql - 从列中提取年份并更新另一列 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
谢谢!
解决方案
这是一个坏主意。您始终可以在 Select 上提取年份。当日期更新但年份列没有更新时会发生什么。如果您必须存储它并使用 Postgres 12(或更高版本),请考虑将其创建为生成的列。所以
alter table add column year integer generated always as (extract (year from tdate)) stored;
这避免了更新问题上面的问题。
警告:年份并不是一个好的列名。虽然不是 Postgres保留字,但它是 SQL 标准保留字。这可能会导致将来出现意外错误。
推荐阅读
- visual-studio - Visual Studio 2015 中的查找和替换不将所选字符串作为默认值
- asp.net-mvc - ASP.NET 应用程序 - 限制 Microsoft 身份验证订阅者
- html - 图像无法在移动视图上正确显示
- postgresql - 如何在 EXCLUDE 约束中将 uuid 与 postgresql gist 一起使用
- python - Datetime - Strftime and Strptime
- powershell - Get wmi object process and create a command doesn't work
- sql - Vertica/SQL:获取行立即处理事件
- datanucleus - 来自 DataNucleus 初始化的警告:数据库适配器(JDBC 驱动程序)不支持表定义中的模式名称规范
- python - PYTHON:更改列名
- python - How to get the cluster to which a cell belongs, using AllenSDK?