我正在使用Sequelize,我一直遇到问题需要获得列的MAX
var userId = req.body.userId;
Sensor.findAll(
{
where : {
userId : userId
},
attributes: [
sequelize.fn('MAX', sequelize.literal('temperature'))
],
include: [{
model: models.Temperature
}]
}).then(function(sensor_result) {
res.status(200).json({ status:"success", data: sensor_result });
}).catch(function(error) {
console.log(error);
res.status(409).json({ status:"error", data: null, message:"Something went wrong, please try again." });
})
这样可行,但如果我将温度列更改为cratedAt列,则会导致出现问题" ER_NON_UNIQ_ERROR:Column' createdAt'在字段列表中是不明确的"
var userId = req.body.userId;
Sensor.findAll(
{
where : {
userId : userId
},
attributes: [
sequelize.fn('MAX', sequelize.literal('createdAt'))
],
include: [{
model: models.Temperature
}]
}).then(function(sensor_result) {
res.status(200).json({ status:"success", data: sensor_result });
}).catch(function(error) {
console.log(error);
res.status(409).json({ status:"error", data: null, message:"Something went wrong, please try again." });
})
临时解决方案就是这个,但它根本没有效率
Sensor.findAll(
{
where : {
userId : userId
},
include: [{
model: models.Temperature,
order: [['createdAt', 'DESC']],
limit: 1
}]
}).then(function(sensor_result) {
res.status(200).json({ status:"success", data: sensor_result });
}).catch(function(error) {
res.status(409).json({ status:"error", data: null, message:"Something went wrong, please try again." });
})
所以我想知道是否有任何选项可以获取createdAt列的MAX值