我有一个 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 正在尝试将结果映射到价格模型 - 使用 raw: true
来防止这种情况发生。
Price.findAll({
attributes: [Sequelize.fn('max', Sequelize.col('id'))],
group: ["symbol"],
raw: true,
})
关于javascript - 如何使用 Sequelize.js 获取 MAX(id) GROUP BY 其他字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51916911/