将 varchar 列升级为 postgresql 中的枚举类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15655820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:51:00  来源:igfitidea点击:

Upgrading a varchar column to enum type in postgresql

sqldatabasepostgresqlddl

提问by Gopal

We have a varchar column in a table, that we need to upgrade to enum type.

我们在表中有一个 varchar 列,我们需要升级到 enum 类型。

All the values in the varchar column are valid values in the enumeration. There is no null values in the varchar column.

varchar 列中的所有值都是枚举中的有效值。varchar 列中没有空值。

ALTER TABLE tableName
   ALTER COLUMN varcharColumn TYPE enum_type

ERROR: column "varcharColumn" cannot be cast to type enum_type SQL state: 42804

错误:无法将列“varcharColumn”强制转换为类型 enum_type SQL 状态:42804

The round about way is to

迂回的方式是

  1. Create another new column with enum type.
  2. Update the enum type column with the varchar column after typecasting.
  3. Drop the varchar column.
  4. Rename the enum type column name to the varchar column name.
  1. 使用枚举类型创建另一个新列。
  2. 类型转换后使用 varchar 列更新枚举类型列。
  3. 删除 varchar 列。
  4. 将枚举类型列名重命名为 varchar 列名。

Is there a better way to achieve this?

有没有更好的方法来实现这一目标?

Thanks in advance.

提前致谢。

回答by a_horse_with_no_name

You need to define a cast to be used because there is no default cast available.

您需要定义要使用的演员表,因为没有可用的默认演员表。

If all values in the varcharColumncomply with the enum definition, the following should work:

如果中的所有值都varcharColumn符合枚举定义,则以下内容应该有效:

alter table foo 
  ALTER COLUMN varcharColumn TYPE enum_type using varcharColumn::enum_type;

I personally don't like enums because they are quite unflexible. I prefer a check constraint on a varchar column if I want to restrict the values in a column. Or - if the list of values changes often and is going to grow - a good old "lookup table" with a foreign key constraint.

我个人不喜欢枚举,因为它们非常不灵活。如果我想限制列中的值,我更喜欢对 varchar 列的检查约束。或者 - 如果值列表经常变化并且会增长 - 一个带有外键约束的旧“查找表”。

回答by Gopal

Got it.

知道了。

ALTER TABLE tableName
   ALTER COLUMN varcharColumn TYPE enum_type
    USING varcharColumn::enum_type

will update it successfully.

将成功更新它。

回答by qrtLs

you as well might consider domain type if you dont need the enum ordering property and are offput by missing delete enum value.
Domain types are user-denfiend types + constraints, which makes x out of a selection possible via CHECK& co and as such not so 'unwieldy like enums.

如果您不需要枚举排序属性并且因缺少删除枚举值而被取消,您也可以考虑域类型。
域类型是用户定义的类型 + 约束,这使得 x 可以通过CHECK& co进行选择,因此不像枚举那样“笨拙”。

Typical enum is eg log levels, while domain eg email text input validation with the field being present in many tables.

典型的枚举是例如日志级别,而域例如电子邮件文本输入验证,该字段存在于许多表中。