如何使用Sequalize.js获取MAX(id)GROUP BY other_field?

时间:2018-08-19 10:51:33

标签: javascript mysql sql node.js sequelize.js

我有一个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 },

1 个答案:

答案 0 :(得分:2)

Sequelize尝试将结果映射到Price模型-使用raw: true可以防止这种情况。

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