数据库为DB2 V9.1
有一张表,字段只有两个:ROLE_ID, AUTHORITY_ID,关系为多对多。
例如有如下数据:
ROLE_ID AUTHORITY_ID
-------- ----------
A 1
A 2
B 2
B 3
C 1
需求:写一个sql查询语句,在新增role的之前,要检查数据库是否存在重复AUTHORITY_ID的role
根据上面的需求和数据,要实现的效果为:
如果新增的ROLE的AUTHORITY_ID为(1),查找数据库会发现与C重复;
如果新增的ROLE的AUTHORITY_ID为(1, 2),查找数据库会发现与A重复;
如果新增的ROLE的AUTHORITY_ID为(1, 2,3),查找数据库没有重复;
如果新增的ROLE的AUTHORITY_ID为(3),查找数据库没有重复;
(也就是说,只有AUTHORITY_ID的完全相等才算重复,少或者多都不算重复)
请问这个sql查询语句怎么写呢?第一感觉是要group by ROLE_ID,但是接下来怎么在分组里面比较呢?
------解决方案--------------------------------------------------------
select distinct e.role_id from role_quest e
left join (
select
case when c.role_id is null then d.role_id
else c.role_id end as role_id
from role_quest c
full outer join (
select distinct a.role_id,b.id from role_quest a,
(
select * from (
values ('2'),('3')
) as tt(id)
) b
) d
on c.role_id=d.role_id and c.authority_id=d.id
where c.role_id is null or d.role_id is null ) f
on e.role_id=f.role_id
where f.role_id is null