我有一个mysql数据库,该数据库存储用符号表示的某些产品的价格。我现在想获取每个符号的最新价格。在纯mysql中,我可以运行以下命令:
SELECT *
FROM prices
WHERE id IN (SELECT MAX(id) FROM prices GROUP BY symbol);
我现在想使用Sequelize.js进行相同的操作。因此,我尝试了以下几种变体:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('mmjs', 'root', 'xxx', {host: 'localhost', dialect: 'mysql', logging: false, pool: {max: 5, min: 1, idle: 20000, acquire: 30000, handleDisconnects: true}, operatorsAliases: false,});
const Price = sequelize.define('price', {
createdAt: {type: Sequelize.DATE(6), allowNull: false},
symbol: {type: Sequelize.STRING, allowNull: false},
bid: {type: Sequelize.FLOAT},
ask: {type: Sequelize.FLOAT},
});
Price.findAll({
attributes: [Sequelize.fn('max', Sequelize.col('id'))],
group: ["symbol"]
}).then((maxIds) => {
console.log(maxIds);
console.log(maxIds.length); // logs the correct length of 82
return Price.findAll({
where: {
id: {
[Sequelize.Op.in]: maxIds
}
}
});
}).then(maxPrices => {
console.log(maxPrices);
});
如评论中所述,
maxIds.length
记录正确的长度为82。但是在那之后,我得到一个错误,说Unhandled rejection Error: Invalid value price
。此外,console.log(maxIds);
给了我一些似乎没有期望的最大id值的对象。下面是一个这样的对象的示例。有人知道我在做什么错吗?为什么不像查询
SELECT MAX(id) FROM prices GROUP BY symbol
一样给我最大ID?欢迎所有提示!
price {
dataValues: {},
_previousDataValues: {},
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
sequelize: [Object],
hooks: {},
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
最佳答案
Sequelize尝试将结果映射到Price模型-使用raw: true
可以防止这种情况。
Price.findAll({
attributes: [Sequelize.fn('max', Sequelize.col('id'))],
group: ["symbol"],
raw: true,
})