我有一个基本的sql问题。我通过联结表有很多对很多的关系。通过EmployeeRoles说员工担任角色
Table: EMPLOYEES
Columns: id, name, etc.
Table: ROLES
Columns: id, name
Table: EMPLOYEES_ROLES
Columns: employee_id, role_id
我如何查询具有两个角色的员工,例如Admin和Supervisor?休眠中的奖励积分。
答案 0 :(得分:2)
您可以在下面尝试-
select a.emp_id,b.name from employee_roles a
inner join EMPLOYEES b on a.emp_id=b.id
inner join roles c on a.role_id=c.id
where c.name in ('Admin' ,'Supervisor') and not exists
(select 1 from employee_roles a1
inner join EMPLOYEES b1 on a1.emp_id=b1.id
inner join roles c1 on a1.role_id=c1.id
where a.emp_id=a1.emp_id and c1.name='Trainee')
group by a.emp_id,b.name
having count(distinct c.name)=2
答案 1 :(得分:0)
如果您不需要知道员工具有哪些特定角色,则甚至不需要访问角色表;只需获取在employee_roles中具有多个记录的employee_id号的列表,然后将这些employee_id值加入雇员即可:
select e.name, count(x.role_id) as num_roles
from employee_roles x
join employees e
on (e.id = x.employee_id)
having count(x.role_id) >= 2;