首页 > 解决方案 > 如何使用 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 },

标签: javascriptmysqlsqlnode.jssequelize.js

解决方案


Sequelize 正在尝试将结果映射到价格模型 - 用于raw: true防止这种情况。

Price.findAll({
    attributes: [Sequelize.fn('max', Sequelize.col('id'))],
    group: ["symbol"],
    raw: true,
})

推荐阅读