You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何将存储UUID的varchar列转为UUID数组列

PostgreSQL将单UUID值转为UUID数组列的解决方案

场景说明

已完成前置操作:

  • 创建to_user_copy列备份原to_user的UUID数据(原列类型为varchar)
  • 删除原to_user列,执行ALTER TABLE "transactions" ADD "to_user" character varying array创建新的varchar数组列
  • 当前to_user列值全为NULL,需将to_user_copy中的单UUID转为数组形式存入新列

核心更新语句

执行以下SQL完成数据转换:

UPDATE "transactions"
SET "to_user" = ARRAY["to_user_copy"]::varchar[]
WHERE "to_user_copy" IS NOT NULL;

语句解释

  • ARRAY["to_user_copy"]:利用PostgreSQL数组构造函数,将单个UUID值包装为数组格式
  • ::varchar[]:显式类型转换,确保结果与新列的character varying array类型完全匹配
  • WHERE "to_user_copy" IS NOT NULL:跳过空值记录,避免将NULL转为{NULL}数组(若需保留空值为NULL则保留此条件)

验证结果

执行查询确认转换效果:

SELECT "to_user_copy", "to_user" FROM "transactions";

预期返回结果:

to_user_copy                |        to_user
---------------------------------------------------------------                
dc2544a6-5a5b-4268-9f31-9a9f8bae58aa  | {dc2544a6-5a5b-4268-9f31-9a9f8bae58aa}

ORM映射确认

已配置的TypeORM映射符合要求,应用层可直接用string[]类型处理数组数据:

@Column("varchar", {name:'to_user', array: true })
toUser: string[];

内容的提问来源于stack exchange,提问作者Shanthan Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:45:45