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

Prisma查询:如何判断字段字符串值是否存在于指定目标字符串中

实现方案

方案1:使用Prisma原生SQL表达式(推荐)

Prisma支持在查询中嵌入原生SQL片段,你可以直接调用对应数据库的位置查找函数实现需求,性能最优,写法如下:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

const targetStr = "some random string containing the value in comment"
const result = await prisma.你的表名.findMany({
  where: Prisma.sql`POSITION(comment IN ${targetStr}) > 0`
})

不同数据库的函数语法略有差异,按需替换即可:

  • PostgreSQL:POSITION(comment IN ${targetStr}) > 0
  • MySQL:LOCATE(comment, ${targetStr}) > 0
  • SQL Server:CHARINDEX(comment, ${targetStr}) > 0
    用Prisma.sql参数化传参可以自动处理转义,避免SQL注入风险,不要手动拼接字符串

方案2:应用层过滤后IN查询(仅适合小表场景)

如果你的表数据量非常小,也可以先取出所有待匹配的字段值,在应用层过滤后再用IN查询:

const targetStr = "some random string containing the value in comment"
// 先查询所有非空的comment字段值
const allComments = await prisma.你的表名.findMany({
  select: { comment: true },
  where: { comment: { not: null } }
})
// 过滤出存在于目标字符串中的值
const matchedComments = allComments
  .map(item => item.comment)
  .filter(comment => targetStr.includes(comment))
// 用IN查询拿到最终匹配结果
const result = await prisma.你的表名.findMany({
  where: { comment: { in: matchedComments } }
})

该方案需要两次查询,数据量较大时性能很差,仅作为临时替代方案使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 07:09:00