javascript - 如何使用 Sequalize.js 获取 MAX(id) GROUP BY other_field?
问题描述
我有一个 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 值。下面是一个这样的对象的示例。
有人知道我在这里做错了什么吗?为什么它不像查询一样给我最大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 },
解决方案
Sequelize 正在尝试将结果映射到价格模型 - 用于raw: true
防止这种情况。
Price.findAll({
attributes: [Sequelize.fn('max', Sequelize.col('id'))],
group: ["symbol"],
raw: true,
})
推荐阅读
- json - 无法在没有映射或任何列表视图的情况下访问 json 数组项本机反应
- abap - 由于内部表为空,读取语句失败
- android - 网格视图旋转处理
- ruby - 替换散列中的每个键
- java - java.lang.NoClassDefFoundError: com/trueaccord/scalapb/GeneratedEnum
- mysql - 我可以使用查询输入参数来获得不同的 where 条件吗?(类似于 IF 语句)
- angular - nvd3 折线图中的刻度数不一致。
- php - Mysql(学说)可能由于分组而重复计数结果,但无法弄清楚
- typo3 - TYPO3 中 addModule 和 registerModule 的区别
- java - Spring Boot 到 Postgres 数据库 - 驱动程序问题