按计数和其他列分页顺序排序

时间:2019-08-09 18:50:08

标签: sql sql-server pagination sequelize.js associations

我有两个表UsersRepairCenters,它们通过repairCentersUsers表具有多对多关系。使用Sequelize,如何从Users中获取所有条目,这些条目按与RepairCenters关联的User的数量和由分页的RepairCenter.name进行排序?

模型

module.exports = (sequelize, DataTypes) => {
  const Users = sequelize.define(
    "Users",
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: {
            args: true,
            msg: "Name cannot be empty."
          },
          notNull: {
            args: true,
            msg: "Name cannot be null."
          }
        }
      }
    },
  );

  Users.associate = models => {
    Users.belongsToMany(models.RepairCenters, {
      as: "RepairCenters",
      through: "repairCentersUsers",
      foreignKey: "userId"
    });
  };

  return Users;
};

module.exports = (sequelize, DataTypes) => {
  const RepairCenters = sequelize.define("RepairCenters", {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: {
          args: true,
          msg: "Name cannot be empty."
        },
        notNull: {
          args: true,
          msg: "Name cannot be null."
        }
      }
    }
  });

  RepairCenters.associate = models => {
    RepairCenters.belongsToMany(models.Users, {
      as: "Users",
      through: "repairCentersUsers",
      foreignKey: "repairCenterId"
    });
  };

  return RepairCenters;
};

我尝试过的查询

let { count, rows } = await Users.findAndCountAll({
      offset: (page - 1) * length,
      limit: length,
      attributes: {
        include: [
          [
            Sequelize.literal(
              "(SELECT COUNT(*) FROM [repairCentersUsers] WHERE [repairCentersUsers].[userId] = [Users].[id])"
            ),
            "RepairCentersCount"
          ]
        ]
      },
      include: [{ model: RepairCenters, as: "RepairCenters" }],
      order: [
        [Sequelize.literal("RepairCentersCount"), orderDirection],
        [RepairCenters, "name", orderDirection]
      ],
      distinct: true
    });

这将产生以下SQL:

SELECT [Users].*,
       [RepairCenters].[id]                                                    AS [RepairCenters.id],
       [RepairCenters].[name]                                                  AS [RepairCenters.name],
       [RepairCenters->repairCentersUsers].[createdAt]                         AS [RepairCenters.repairCentersUsers.createdAt],
       [RepairCenters->repairCentersUsers].[updatedAt]                         AS [RepairCenters.repairCentersUsers.updatedAt],
       [RepairCenters->repairCentersUsers].[repairCenterId]                    AS [RepairCenters.repairCentersUsers.repairCenterId],
       [RepairCenters->repairCentersUsers].[userId]                            AS [RepairCenters.repairCentersUsers.userId] 
  FROM (SELECT [Users].[id],
       [Users].[name],
       (SELECT COUNT(*) 
  FROM [repairCentersUsers] 
 WHERE [repairCentersUsers].[userId] = [Users].[id])                     AS [RepairCentersCount] 
  FROM [Users]                                                            AS [Users] 
ORDER BY RepairCentersCount DESC OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY) AS [Users] LEFT OUTER JOIN ( [repairCentersUsers] AS [RepairCenters->repairCentersUsers] 
INNER JOIN [RepairCenters]                                              AS [RepairCenters] 
    ON [RepairCenters].[id] = [RepairCenters->repairCentersUsers].[repairCenterId]) 
    ON [Users].[id] = [RepairCenters->repairCentersUsers].[userId] 
ORDER BY RepairCentersCount DESC,
       [RepairCenters].[name] DESC;

问题在于ORDER BY, OFFSET AND LIMITRepairCenters在子查询中。如何将ORDER BY, OFFSET AND LIMIT置于此子查询的外部?

0 个答案:

没有答案