使用Sequelize进行分组聚合查询报错 Column ‘id’ in field list is ambiguous

2022-07-27,,,,

1.用到的技术栈 Eggjs + TypeScript + React + Mysql

功能需求描述:有两张表分别为 【用户diy关卡表】【游戏记录表】 两张表的表名分别为 【game_diy_info】【save_data】,现在要通过  【用户diy关卡表】的 id 去关联查询 【游戏记录表】的 gid 然后聚合分组统计出 【游戏记录表】出现的记录数,最后把它展示再 Echarts 的折线图上面。

  • service 层
import { Service } from 'egg';
import Sequlize from 'sequelize';
const Op = Seuqelize.Op;

export default class SummaryService extends Service {
    // 获取用户 DIY 关卡玩家的记录数
    public async findEcharsList() {
        const { ctx } = this;
        return ctx.model.GameDiyInfo.findAll({
            order: [[ 'id': 'DESC' ]],
            include: [
                {
                    model: ctx.model.SaveData,
                    as: 'savePage',
                    attribute: ['gid', 'type']
                }
            ],
            // 分组聚合统计
            attributes: ['id', [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']],
            group: 'id',
            raw: true
        })
    } 
}
  • 前端进行请求这个接口的时候就会报一个错 Column ‘id’ in field list is ambiguous

问题描述:就是 id 重复了,其实就是两张表有相同的字段,但是使用时表字段的名称前没有加表名,前面加上前缀 表名.id 就没问题了。改进的代码如下:

import { Service } from 'egg';
import Sequlize from 'sequelize';
const Op = Seuqelize.Op;

export default class SummaryService extends Service {
    // 获取用户 DIY 关卡玩家的记录数
    public async findEcharsList() {
        const { ctx } = this;
        return ctx.model.GameDiyInfo.findAll({
            order: [[ 'id': 'DESC' ]],
            include: [
                {
                    model: ctx.model.SaveData,
                    as: 'savePage',
                    attribute: ['gid', 'type']
                }
            ],
            /* start-- 改进后 */
            attributes: ['id', [Sequelize.fn('COUNT', Sequelize.col('game_diy_info.id')), 'count']],
            group: 'game_diy_info.id',
            /* end-- 改进后 */
            raw: true
        })
    } 
}

 

本文地址:https://blog.csdn.net/HANGSOME123/article/details/110191365

《使用Sequelize进行分组聚合查询报错 Column ‘id’ in field list is ambiguous.doc》

下载本文的Word格式文档,以方便收藏与打印。