SQL 查询以获取只有一个指定角色的用户
SQL query to get users who have only single specified role
目标: 我想过滤掉只分配了一个指定角色的用户。
预期结果:应显示具有指定角色 ID 的用户 ID
实际结果:我得到分配了多个指定角色的用户 ID。
错误消息:没有错误消息
我做了什么:
我有两个 table
第一个是 user_profile,另一个是 user_profile_role。我加入这 2 tables 以过滤掉角色 ID 为 10005 的用户。一些用户包含多个角色 ID。一些用户只包含角色 ID 10005。
我只想列出角色 ID 为 10005 的用户。但他们不应该包含非其他角色 ID。
下面是我的user_profiletable
id
enabled
2222
1
3333
1
4444
1
5555
1
下面是我的 user_profile_role table
id
role_id
2222
10005
2222
10004
3333
10005
4444
10005
5555
10004
5555
10005
我使用下面的 SQL 查询来过滤掉上面提到的内容。但我的 sql 查询似乎没有输出所需的结果。
select distinct u.id,u.enabled,ur.role_id
from USER_PROFILE u right outer join USER_PROFILE_ROLE ur
on u.id=ur.id
where u.enabled=1 AND ur.role_id='10005';
当我 运行 以上查询时,我得到如下输出(这不是我想要的)
id
enabled
role_id
2222
1
10005
3333
1
10005
4444
1
10005
5555
1
10005
下面是我想要的输出
id
enabled
role_id
3333
1
10005
4444
1
10005
如果有人能指出我在 sql 查询中遗漏的内容并指出方向,我将不胜感激。
你可以这样做:
select id, enabled
from (
select
u.id,
u.enabled,
sum(case when r.role_id = 10005 then 1 else 0 end) as cnt_searched,
count(*) as cnt
from user_profile u
join user_profile_role r on r.id = u.id
where u.enabled = 1
group by u.id, e.enabled
) x
where cnt_searched = cnt
目标: 我想过滤掉只分配了一个指定角色的用户。
预期结果:应显示具有指定角色 ID 的用户 ID
实际结果:我得到分配了多个指定角色的用户 ID。
错误消息:没有错误消息
我做了什么: 我有两个 table
第一个是 user_profile,另一个是 user_profile_role。我加入这 2 tables 以过滤掉角色 ID 为 10005 的用户。一些用户包含多个角色 ID。一些用户只包含角色 ID 10005。
我只想列出角色 ID 为 10005 的用户。但他们不应该包含非其他角色 ID。
下面是我的user_profiletable
id | enabled |
---|---|
2222 | 1 |
3333 | 1 |
4444 | 1 |
5555 | 1 |
下面是我的 user_profile_role table
id | role_id |
---|---|
2222 | 10005 |
2222 | 10004 |
3333 | 10005 |
4444 | 10005 |
5555 | 10004 |
5555 | 10005 |
我使用下面的 SQL 查询来过滤掉上面提到的内容。但我的 sql 查询似乎没有输出所需的结果。
select distinct u.id,u.enabled,ur.role_id
from USER_PROFILE u right outer join USER_PROFILE_ROLE ur
on u.id=ur.id
where u.enabled=1 AND ur.role_id='10005';
当我 运行 以上查询时,我得到如下输出(这不是我想要的)
id | enabled | role_id |
---|---|---|
2222 | 1 | 10005 |
3333 | 1 | 10005 |
4444 | 1 | 10005 |
5555 | 1 | 10005 |
下面是我想要的输出
id | enabled | role_id |
---|---|---|
3333 | 1 | 10005 |
4444 | 1 | 10005 |
如果有人能指出我在 sql 查询中遗漏的内容并指出方向,我将不胜感激。
你可以这样做:
select id, enabled
from (
select
u.id,
u.enabled,
sum(case when r.role_id = 10005 then 1 else 0 end) as cnt_searched,
count(*) as cnt
from user_profile u
join user_profile_role r on r.id = u.id
where u.enabled = 1
group by u.id, e.enabled
) x
where cnt_searched = cnt