我的数据库中有以下表格
|id|name |company_id|role |
|1 |test1|11 |READADMIN |
|2 |test2|11 |WRITEADMIN |
|3 |test3|11 |READWRITEADMIN |
|4 |test4|12 |READADMIN |
|5 |test5|12 |WRITEADMIN |
|6 |test6|12 |READWRITEADMIN |
|7 |test6|11 |READADMIN |
|8 |test7|13 |READADMIN |
|9 |test8|12 |READADMIN |
|10|test9|12 |READADMIN |
我的目标是提取具有相同READADMIN
角色company_id
的所有管理员,此用户的数量应该超过1。
总的来说,我希望得到以下结果:
|id|name |company_id|role |
|1 |test1|11 |READADMIN|
|7 |test6|11 |READADMIN|
|4 |test4|12 |READADMIN|
|9 |test8|12 |READADMIN|
|10|test9|12 |READADMIN|
我已在下方创建了选择,但我不确定其准确性和效果:
SELECT id, name, company_id, role
FROM admin
WHERE company_id IN(SELECT CO.id
FROM company CO
join admin AU
ON CO.id = AU.company_id
WHERE role = 'READADMIN'
GROUP BY CO.id
HAVING Count(AU.id) > 1)
AND role = 'READADMIN';
了解上述任务的最佳方法会很好。
答案 0 :(得分:1)
我想这会工作:
SELECT DISTINCT id, name, company_id, role
FROM admin WHERE role='READADMIN' GROUP BY CO.id
我不确定你的意思。我从您的问题中理解的是,您希望让所有用户认为他们的角色是' READADMIN'而且你不希望结果中有任何重复。
答案 1 :(得分:1)
SELECT a.*
FROM admin a
WHERE a.role = 'READADMIN'
AND EXISTS ( SELECT 'a'
FROM admin a2
WHERE a2.role = a.role
AND a2.company_id = a.company_id
AND a2.id <> a.id
)
答案 2 :(得分:0)
为什么不:
SELECT id, name, company_id, role
FROM admin
WHERE role = 'READADMIN'
GROUP BY company_id
HAVING Count(company_id) > 1
;
答案 3 :(得分:0)
以下代码段应仅授予对表的一次访问权限,更好地检查自己的计划。
select id,
name,
company_id,
role
from (
select id,
name,
company_id,
role,
count(distinct id) over (partition by company_id) as cn
from admin
where role = 'READADMIN'
)
where cn > 1;
答案 4 :(得分:0)
我会做这样的事情。如果你已经有一个实际的表,显然你不需要with
:
with admin as
(select 1 id,'test1' name,11 company_id, 'READADMIN' role from dual
union
select 2 id,'test2' name,11 company_id, 'WRITEADMIN' role from dual
union
select 3 id,'test3' name,11 company_id, 'READWRITEADMIN' role from dual
union
select 4 id,'test4' name,12 company_id, 'READADMIN' role from dual
union
select 5 id,'test5' name,12 company_id, 'WRITEADMIN' role from dual
union
select 6 id,'test6' name,12 company_id, 'READWRITEADMIN' role from dual
union
select 7 id,'test6' name,11 company_id, 'READADMIN' role from dual
union
select 8 id,'test7' name,13 company_id, 'READADMIN' role from dual
union
select 9 id,'test8' name,12 company_id, 'READADMIN' role from dual
union
select 10 id,'test9' name,12 company_id, 'READADMIN' role from dual)
select admin.id, admin.name, admin.company_id, admin.role
from admin
inner join
(select company_id, role
from admin
where role = 'READADMIN'
group by company_id, role having count(*) > 1) grouped
on admin.company_id = grouped.company_id
and admin.role = grouped.role;