代码之家  ›  专栏  ›  技术社区  ›  kramer65

如何使用Sequalize.js按其他字段获取MAX(id)GROUP?

  •  1
  • kramer65  · 技术社区  · 6 年前

    我有一个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 },
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   m1ch4ls    6 年前

    Sequelize正在尝试将结果映射到价格模型-使用 raw: true

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