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
相关产品推荐
相关产品推荐

