查找不在组织中的用户
给定以下数据:
users
id name
== ====
1 Alice
2 Bob
3 Carl
organizations
id name
== ====
1 Aaa
2 Bbb
memberships
id organization_id user_id
== =============== =======
1 1 1
2 2 1
3 1 2
我想查找不属于特定组织的用户 X:
根本没有成员记录的用户
并且
有会员记录的用户,但不属于组织 X。
例如,我想要不在组织 2 中的用户。我期望:
users.id
========
2
3
尝试此连接不起作用:
SELECT *
FROM users left join memberships on memberships.user_id = users.id
where memberships.id is null or memberships.organization_id <> 1
它返回用户 1,2,3,因为 1 与第二个 where 条件匹配。
有没有有效的方法来做到这一点?
Given this data:
users
id name
== ====
1 Alice
2 Bob
3 Carl
organizations
id name
== ====
1 Aaa
2 Bbb
memberships
id organization_id user_id
== =============== =======
1 1 1
2 2 1
3 1 2
I want to find users that do not belong to a particular organization X:
users with no membership records at all
AND
users with membership records, but not for organization X.
For example, I want users that are not in organization 2. I am expecting:
users.id
========
2
3
Attempting with this join isn't working:
SELECT *
FROM users left join memberships on memberships.user_id = users.id
where memberships.id is null or memberships.organization_id <> 1
It's returning users 1,2,3 since 1 matches on the second where condition.
Is there an efficient way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将您的 JOIN 限制为 2 的组织,然后测试 null 是执行您正在寻找的操作的一种方法,例如
您也可以使用
NOT IN
Restricting your JOIN to organization of 2 and then testing for null is the one way to do what you're looking for e.g.
You can also use
NOT IN
您还可以使用减集运算符:
从用户中选择“名称”
减
从用户中选择“名称” u 内部加入成员资格 m 上 u.id = m.user_id 内部加入组织 o 上 m.organization_id = o.id 和 o."name" = 'X'
You can also use the minus set operator:
select "name" from users
minus
select "name" from users u inner join memberships m on u.id = m.user_id inner join organizations o on m.organization_id = o.id and o."name" = 'X'
这是使用存在子句的另一个选项:
Here's another option using the exists clause:
编辑:修改为包括所有用户
EDIT: modified to include all users