新手问题 更改已有数据的字段的数据类型

ZhouYiYu · 2017年08月15日 · 最后由 ZhouYiYu 回复于 2017年08月15日 · 1832 次阅读

我想更改一个字段的数据类型,将其从 string 换成 integer,并更改其名字
1,但这个字段之前已经有了数据,数据不能抛弃,我应该怎么更改合适?
2,我的想法是,创建一个新的 interger 字段,将原本字段的数据迁移到新的字段,请问有没有办法实现?
相当于:
我想要一个新的字段,如何把旧字段的数据迁移到新的字段?

按照 pg 的文档,只要现有数据都可以转换成整数,只需要更改字段类型

“This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a USING clause that specifies how to compute the new values from the old.”

https://www.postgresql.org/docs/current/static/ddl-alter.html

nouse 回复

可是我的旧数据不是 integer,可能我描述的不是很清楚,现在我需要做的如下: 1,就是我之前设置的字段,假如是 a,a 为 string 类型,所以我通过 a 存到数据库的数据的类型全部为 string 2,现在我创建了一个表,通过 id 去映射字段 a,但现在有个问题,我之前通过 a 存到数据库的数据为 string,现在在数据库中这些数据应该出现的类型是 integer,而且这些数据是需要的,我应该怎么做?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号