请求错误:列 " " 在 ORDER BY 子句中无效,因为它未包含在聚合函数或 GROUP BY 子句中



我有两个使用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: Column "transactions.id">

在ORDER BY子句中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。默认情况下似乎序列化返回'id'列。我怎么解决这个问题?

所以底层生成的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']
})

最新更新