我与organizaiton_member
和user
表之间的联结organization
存在多对多关系。我正在尝试创建一个查询,计算organization_id
与特定整数匹配的user_id的数量。我结束时的预期结果是一行,user_ids的总数为一列,organization_Id为第二列。我认为我可以通过以下查询实现此目的,但是我收到错误Unhandled rejection SequelizeDatabaseError: column "user.user_id" must appear in the GROUP BY clause or be used in an aggregate function
。是否有必要这样做?很抱歉,缺乏使用SQL涉及聚合和多对多的经验。
查询:
models.User.findAll({
attributes: [[sequelize.fn('COUNT', sequelize.col('user.user_id')), 'user_count']],
include: [{
model: models.Organization,
where: {
organizationId: req.session.organizationId
},
attributes: ['organization_id'],
group: ['organiztion.organization_id']
}],
})
用户架构:
user_id
first_name
last_name
email
组织架构:
organization_id
org_name
Organization_Member架构:
user_id
organization_id
SQL生成:
SELECT "user"."user_id" AS "userId",
Count("user"."user_id") AS "user_count",
"organizations"."organization_id" AS
"organizations.organizationId",
"organizations"."organization_id" AS
"organizations.organization_id",
"organizations.organization_member"."created_at" AS
"organizations.organization_member.created_at",
"organizations.organization_member"."updated_at" AS
"organizations.organization_member.updated_at",
"organizations.organization_member"."user_id" AS
"organizations.organization_member.user_id",
"organizations.organization_member"."organization_id" AS
"organizations.organization_member.organization_id"
FROM "user" AS "user"
INNER JOIN ("organization_member" AS "organizations.organization_member"
INNER JOIN "organization" AS "organizations"
ON "organizations"."organization_id" =
"organizations.organization_member"."organization_id")
ON "user"."user_id" = "organizations.organization_member"."user_id"
AND "organizations"."organization_id" = 1;