我有user_role表,可以为一个用户分配多个角色。我想要一个查询,该查询将检查是否为特定用户分配了“管理员”或“超级管理员”角色(将来可能需要检查更多角色)。我尝试通过使用PLSQL来做到这一点,方法是为用户选择每个角色并将其传递给变量,然后检查这些选定角色中的任何一个是否为'admin'或'superadmin'。它变得有点复杂。我该如何解决这个问题?
答案 0 :(得分:0)
像这样吗?
SQL> with user_role (user_id, role) as
2 (select 1, 'admin' from dual union all
3 select 1, 'superadmin' from dual union all
4 select 2, 'clerk' from dual union all
5 select 2, 'superadmin' from dual union all
6 select 3, 'manager' from dual
7 )
8 select user_id,
9 max (case when role in ('admin', 'superadmin') then 'yes' else 'no' end ) is_admin
10 from user_role
11 group by user_id
12 order by user_id;
USER_ID IS_ADMIN
---------- ----------
1 yes
2 yes
3 no
SQL>
答案 1 :(得分:0)
如果需要特定用户,可以执行以下操作:
select (case when exists (select 1
from user_role ur
where ur.role in ('admin', 'superadmin') and user_id = :user_id
)
then 'yes' else 'no'
end) as has_role
from dual