如何在sequelize中使用COUNT,GROUP BY,ORDER BY编写查询

问题描述 投票:2回答:1

我想使用GROUP BY,ORDER BY,COUNT在sequelize ORM中编写查询。

这是我的SQL查询:

SELECT COUNT(1),
       bucket_name,
       clusterId
FROM aidc_tenoco.output_table
WHERE clusterId IS NOT NULL
GROUP BY clusterId
ORDER BY COUNT(1) DESC
LIMIT 0,
      1

我想写下续集请帮帮我。

sequelize.js
1个回答
0
投票

Code

const Op = require("sequelize").Op;
const sequelize = require("../models").sequelize;

models.OutputTable.findOne({
    where: {
      clusterId: {
        [Op.ne]: null,
      },
    },
    attributes: ["bucket_name", "clusterId", [sequelize.fn("COUNT", "1"), "CountedValue"]],
    group: ["clusterId"],
    order: [[sequelize.col("CountedValue"), "DESC"]],
});

Explanation

使用文档 - Querying这是非常简单的。

findOne方法将查询限制为1.属性子句选择column_names。知道sequelize不会识别你的CountedValue列因此order它使用sequelize.col(columnAlias)

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.