我有以下数据模型:
user has_many organization_users
user has_many registrations
a user has a column type
a registration has columns learning_item_type and learning_item_id
查询的目标是检索特定组织中没有注册特定学习项目的所有用户(learning_item_type和learning_item_id的组合(,它必须包括根本没有注册的组织中的用户(左加入(我提出了这个活动记录查询:
User
.joins(:organizations_users)
.left_joins(:registrations)
.where(
type: 'Collaborator',
'organizations_users.organization_id': organization.id
)
.where.not(
'registrations.learning_item_id': learning_item.id,
'registrations.learning_item_type': learning_item.class.to_s
).distinct
在原始sql中看起来像:
"SELECT DISTINCT "users".* FROM "users" INNER JOIN "organizations_users" ON "organizations_users"."user_id" = "users"."id" LEFT OUTER JOIN "registrations" ON "registrations"."account_id" = 28 AND "registrations"."user_id" = "users"."id" WHERE "users"."account_id" = 28 AND "users"."type" = 'Collaborator' AND "organizations_users"."organization_id" = 1 AND NOT ("registrations"."learning_item_id" = 10164 AND "registrations"."learning_item_type" = 'Session')"
我不知道这个查询出了什么问题,但它不断返回实际注册了learning_item_id=10164和learning_item_type"Session"的用户。
为什么这里没有考虑负面的NOT标准?
User.left_joins(:registrations)
加入后,你会得到这样的东西:
users.id | 注册。learning_item_id |
---|---|
1 | 10164 |
1 | 10165 |
2 | 1016 |