Sql NOT IN子句:如何获取不包含括号内所有元素的所有用户
我在获取括号内没有所有角色ID的用户时遇到问题。 如果用户没有这些角色之一,下面的查询将返回该用户Sql NOT IN子句:如何获取不包含括号内所有元素的所有用户,sql,oracle,Sql,Oracle,我在获取括号内没有所有角色ID的用户时遇到问题。 如果用户没有这些角色之一,下面的查询将返回该用户 select user_id from user_group_role group by user_id having sum(case when role_id in (23,98,105,3310,4928,4929,4930) then 1 end) = 0 SQL查询: select user_id,group_id,role_id from user_group_role where
select user_id
from user_group_role
group by user_id
having sum(case when role_id in (23,98,105,3310,4928,4929,4930) then 1 end) = 0
SQL查询:
select user_id,group_id,role_id from user_group_role where role_id not in (23,98,105,3310,4928,4929,4930) ;
用户组角色的示例:
USER_ID GROUP_ID ROLE_ID
---------- --------------- ---------------
3256 2 23
3256 3 98
3256 2 4928
4 2 54
3256 1 4929
3256 1 4930
10256 3 23
62 2 105
700 2 3310
899 2 41
3256 1 105
3256 1 3310
3256 1 4930
62 2 4930
在本例中,用户3256具有所有的角色_id,用户62仅具有4930和105角色_id,用户4没有这些角色_id,在我的情况下,我希望我的查询返回例如用户4
谢谢你的帮助 您需要按每个用户分组,只接受那些没有这些角色的用户
select user_id
from user_group_role
group by user_id
having sum(case when role_id in (23,98,105,3310,4928,4929,4930) then 1 end) = 0
having子句类似于where but,用于数据组,而不仅仅是单个记录。如果您有单独的用户列表,我建议:
select u.*
from users u
where not exists (select 1
from user_group_role ugr
where ugr.user_id = u.user_id and
ugr.role_id in (23, 98, 105, 3310, 4928, 4929, 4930)
);
我建议这样做,因为这将包括不在user\u group\u role表中的用户,因此列表似乎更完整。当然,您可能只需要表中至少有一行的用户,在这种情况下,此查询不需要用户。如果您对用户和角色有唯一的约束,这意味着即使在多个组中,也不能为用户分配两次相同的角色,则可以执行以下操作:
SELECT user_id
FROM user_group_role ugr
GROUP BY user_id
HAVING SUM(
CASE WHEN role_id IN (23,98,105,3310,4928,4929,4930)
THEN 1 ELSE 0 END) < 7
不是全部是指用户没有这些角色,或者用户有一些但不是所有这些角色?