【问题标题】:How to get MAX(id) GROUP BY other_field with Sequalize.js?如何使用 Sequelize.js 获取 MAX(id) GROUP BY 其他字段?
【发布时间】:2019-01-25 18:24:14
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      相关资源
      最近更新 更多