PostgreSQL更新嵌套JSON报错:column "dog_name"不存在求排查
问题描述
我需要编写一条更新查询,将所有养名为“Mark”的狗的员工的country字段更新为“BR”。目标表名为Employees,其中包含JSON类型列additional_options,结构示例如下:
{ 'dog_name': 'Mark' }
我写的SQL语句是:
update "Employees" e set country = "BR" where json_extract_path(e.additional_options, "dog_name") = "Mark"
执行时报错:
column "dog_name" does not exist
补充:用Prisma编写的同名功能代码可正常运行:
export const moveToBrazil = async(): Promise<Employee[]> => { await db.employees.updateMany({ where: { additional_options: { path: ['dog_name'], equals: 'Ellie' } }, data: { country: "BR" } }); return db.employees.findMany({ where: { additional_options: { path: ['dog_name'], equals: 'Ellie' } }, }); }
问题原因与解决方法
- 核心问题:PostgreSQL中,双引号
"用于引用数据库对象(如列名、表名),你把"dog_name"和"Mark"用双引号包裹,数据库会将它们识别为列名而非字符串字面量,因此报错“column 'dog_name' does not exist”。 - 修正后的SQL:将JSON键和匹配值改用单引号
'包裹:
update "Employees" e set country = 'BR' where json_extract_path(e.additional_options, 'dog_name') = 'Mark'
- 更简洁的写法:PostgreSQL支持用
->>操作符直接提取JSON字段的文本值,代码更简洁:
update "Employees" e set country = 'BR' where e.additional_options->>'dog_name' = 'Mark'
为什么Prisma代码能正常运行
Prisma的path: ['dog_name']会自动将数组中的元素处理为字符串字面量,底层生成的SQL会正确使用单引号包裹JSON键,因此不会出现识别错误。
内容的提问来源于stack exchange,提问作者Dean Packard
相关产品推荐
相关产品推荐

