求带GROUP BY的Prisma关联查询语句(对应指定SQL)
实现对应统计需求的Prisma查询
首先需要明确,你的数据库表结构是posts与platforms多对多关联(通过中间表post_platforms),因此原SQL中直接join posts和platforms的写法并不适配多对多关系,需要调整为针对中间表或利用Prisma的关联查询能力来实现统计。
方法1:使用Prisma原生groupBy(推荐)
假设你的Prisma Schema模型定义如下:
model Post { id Int @id @default(autoincrement()) // 其他Post字段 platforms Platform[] @relation("PostPlatform", references: [id]) } model Platform { id Int @id @default(autoincrement()) name String // 其他Platform字段 posts Post[] @relation("PostPlatform", references: [id]) } model PostPlatform { postId Int platformId Int post Post @relation(fields: [postId], references: [id]) platform Platform @relation(fields: [platformId], references: [id]) @@id([postId, platformId]) }
可以直接通过platform.groupBy来统计每个平台关联的帖子数量:
const platformPostStats = await prisma.platform.groupBy({ // 按平台ID和名称分组,对应原SQL的GROUP BY子句 by: ['id', 'name'], // 统计关联的posts数量 _count: { posts: true } }); // 如果需要将结果字段名调整为原SQL的格式(platform_id、count、name) const formattedStats = platformPostStats.map(item => ({ platform_id: item.id, count: item._count.posts, name: item.name }));
方法2:使用原生SQL查询
如果你更倾向于直接执行SQL,可以针对中间表post_platforms编写适配多对多结构的查询,通过Prisma的$queryRaw执行:
const platformPostStats = await prisma.$queryRaw` SELECT pp.platform_id, COUNT(DISTINCT pp.post_id) AS count, pl.name FROM post_platforms pp JOIN platforms pl ON pp.platform_id = pl.id GROUP BY pp.platform_id, pl.name `;
这里使用COUNT(DISTINCT pp.post_id)是为了避免同一帖子关联多个平台时被重复统计,若确认一个帖子只会关联一个平台,也可以简化为COUNT(1)。
内容的提问来源于stack exchange,提问作者Prem
相关产品推荐
相关产品推荐

