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

如何在Prisma中查询至少拥有N条HIGH优先级投诉记录的用户

可行实现方案有两种,可根据你的Prisma版本选择:

方案1:groupBy + having 组合(全版本兼容)

完全匹配你提到的SQL having 实现思路,先统计符合条件的用户ID,再查询完整用户信息:

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

const N = 3; // 替换为你的动态参数

// 1. 筛选出HIGH优先级投诉数>=N的用户ID列表
const qualifiedUserIds = await prisma.complaint.groupBy({
  by: ['userId'],
  where: {
    priority: ComplaintPriority.HIGH
  },
  having: {
    id: {
      _count: {
        gte: N
      }
    }
  }
})

// 2. 查询对应完整用户信息
const targetUsers = await prisma.user.findMany({
  where: {
    id: {
      in: qualifiedUserIds.map(item => item.userId)
    }
  },
  // 可选:同时返回对应用户的所有HIGH优先级投诉
  include: {
    complaints: {
      where: {
        priority: ComplaintPriority.HIGH
      }
    }
  }
})

方案2:关系聚合过滤(Prisma >= 4.16 版本支持)

写法更简洁,一步完成查询,底层会自动生成对应逻辑的SQL:

const N = 3;

const targetUsers = await prisma.user.findMany({
  where: {
    complaints: {
      _count: {
        where: {
          priority: ComplaintPriority.HIGH
        },
        gte: N
      }
    }
  },
  include: {
    complaints: {
      where: { priority: ComplaintPriority.HIGH }
    }
  }
})

两种方案的执行性能和原生手写带having的SQL无明显差异,可根据你的项目实际版本选择即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:07