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

Prisma PostgreSQL queryRaw报42P01错误:表item不存在但实际存在

问题:Prisma原生查询提示表不存在但实际表存在?

问题详情

尝试通过PostgreSQL的SIMILARITY函数,根据name和description字段与搜索值的相似度筛选Item表数据,执行的原生查询语句如下:

let items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`

运行后收到错误:

error - PrismaClientKnownRequestError: 
Invalid `prisma.$queryRaw()` invocation:

Raw query failed. Code: `42P01`. Message: `table "item" does not exist`
  code: 'P2010',
  clientVersion: '4.3.1',
  meta: { code: '42P01', message: 'table "item" does not exist' },
  page: '/api/marketplace/search'
}

但执行以下查询时,能确认Item表确实存在:

let tables = await prisma.$queryRaw`SELECT * FROM pg_catalog.pg_tables;`

解决方案

1. 检查表名大小写

PostgreSQL中,如果创建表时使用双引号包裹表名(如CREATE TABLE "Item" (...)),则表名会区分大小写。此时查询必须用双引号指定正确的大小写:

let items = await prisma.$queryRaw`SELECT * FROM "Item" WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`

未加双引号的item会被PostgreSQL自动转换为全小写,与实际存在的Item表名不匹配,导致报错。

2. 确认表所在的Schema

如果Item表不在默认的publicSchema下,需要在查询中指定Schema:

// 替换your_schema为实际Schema名称
let items = await prisma.$queryRaw`SELECT * FROM "your_schema"."Item" WHERE SIMILARITY(name, ${search}) > 0.4 OR SIMILARITY(description, ${search}) > 0.4;`

可通过pg_catalog.pg_tables的schemaname字段查看表所属的Schema。

3. 验证数据库连接正确性

检查Prisma配置文件(prisma/schema.prisma)中的databaseUrl是否指向了正确的数据库实例和库名,确保两次查询(查Item和查pg_tables)是在同一个数据库上执行的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:45:38