小编典典

RequestError:列“”在 ORDER BY 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句中

sql

我有 2 个使用 sequelize 的表,如下所示

sequelize.define("campaign",{
        id:{
         type:Sequelize.INTEGER,
         autoIncrement:true,
         primaryKey:true,
         allowNull:false
        },
        title:{
            type:Sequelize.STRING
        },
        description:{
            type:Sequelize.STRING
        },
        targetamount:{
            type:Sequelize.INTEGER
        },
        startdate:{
            type:Sequelize.DATE
        },
        enddate:{
            type:Sequelize.DATE

        }
    });
sequelize.define("transaction",{
        id:{
         type:Sequelize.INTEGER,
         autoIncrement:true,
         primaryKey:true,
         allowNull:false
        },
        date:{
            type:Sequelize.DATE
        },
        amount:{
            type:Sequelize.INTEGER
        },
        notes:{
            type:Sequelize.STRING
        }
    });

和与活动关联的表事务

db.Transactions.belongsTo(db.Campaigns);
db.Campaigns.hasMany(db.Transactions,{as:"campaign"});

现在,我正在尝试使用以下代码从交易中收集的金额总和来获取所有广告系列

    const pageSize = 10000;
    const offset = 0;
    Transactions.findAndCountAll({
        attributes: [[Sequelize.fn('sum', Sequelize.col('amount')), 'total']],
        group:['campaignId'],
        limit:pageSize,
        offset:offset
    }).then(async (data)=>{
        ///
    });

但这给出了错误,

RequestError:列“transactions.id”在 ORDER BY 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

默认情况下,似乎续集返回“id”列。我该如何解决这个问题?


阅读 84

收藏
2022-07-21

共1个答案

小编典典

所以在后台生成的 SQL 是无效的。

之所以应用顺序,是因为您要求limitoffset(通常用于分页),这要求排序是确定性的。

为了减轻这种情况,您可以:

  1. 删除limitoffset
  2. 提供ORDER BY在您的分组 ( campaignId) 或聚合 ( total)中的显式

大概是这样的吧?

const pageSize = 10000;
const offset = 0;
Transactions.findAndCountAll({
    attributes: [[Sequelize.fn('sum', Sequelize.col('amount')), 'total']],
    group:['campaignId'],
    limit:pageSize,
    offset:offset,
    order: ['campaignId']
})
2022-07-21