简体   繁体   English

如何更新 postgres 表列并将值设置为和枚举类型

[英]How to update a postgres table column and set the values to and enum type

Say I have a table with two columns假设我有一个包含两列的表

first is called "temp_status", which is an int with values, 0,1,2,3,4 and the other is called "status" which is of type enum, with values, "Enum1", "Enum2", "Enum3", "Enum4", "Enum5",第一个称为“temp_status”,它是一个具有值 0、1、2、3、4 的 int,另一个称为“status”,它是枚举类型,具有值“Enum1”、“Enum2”、“Enum3” ", "枚举4", "枚举5",

I want to assign values to the "status" column based on "temp_status" column.我想根据“temp_status”列为“status”列赋值。 I did the following and got the following error:我做了以下并得到以下错误:


UPDATE "Table"
SET "status" =
CASE
    WHEN "temp_status" = 0 THEN 'Enum1'
    WHEN "temp_status" = 1 THEN 'Enum2'
    WHEN "temp_status" = 2 THEN 'Enum3'
    WHEN "temp_status" = 3 THEN 'Enum4'
    WHEN "temp_status" = 4 THEN 'Enum5'
    ELSE 'Enum1'  -- default value
END
WHERE "temp_status" IN (0, 1, 2, 3, 4);

I got this error;我收到这个错误;

ERROR: column "status" is of type "MyEnumName" but expression is of type text
HINT: You will need to rewrite or cast the expression.

The enum values match so I am wondering how I need to do the casting here枚举值匹配所以我想知道我需要如何在这里进行转换

You're just missing a cast to the enum strings, eg您只是缺少对枚举字符串的强制转换,例如

UPDATE t
SET status =
  CASE
    WHEN temp_status = 0 THEN 'Enum1'::MyEnumName
    WHEN temp_status = 1 THEN 'Enum2'::MyEnumName
    WHEN temp_status = 2 THEN 'Enum3'::MyEnumName
    WHEN temp_status = 3 THEN 'Enum4'::MyEnumName
    WHEN temp_status = 4 THEN 'Enum5'::MyEnumName
    ELSE 'Enum1'  -- default value
  END
WHERE temp_status IN (0, 1, 2, 3, 4);

Note: the default value will never be reached, as the values of temp_status are constraint to values that are already mapped in the case conditions (0, 1, 2, 3, 4).注意:永远不会达到默认值,因为temp_status的值受限于已映射到案例条件 (0, 1, 2, 3, 4) 的值。

However, since your enums can be easily mapped to the column temp_status , you can substantially simplify the update by concatenating 'Enum' and the content of temp_status :但是,由于您的枚举可以很容易地映射到列temp_status ,您可以通过连接'Enum'temp_status的内容来大大简化更新:

UPDATE t 
SET status = ('Enum'||temp_status+1)::MyEnumName
WHERE "temp_status" IN (0, 1, 2, 3, 4);

Demo: db<>fiddle演示: db<>fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM