我有一个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
?
欢迎所有小费!
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 },