mysql count()包含两个表,重复的行数不超过2行

i34xakig  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(339)

我有两张table。
表:员工

表:员工角色

我想显示一个所有员工的列表,其中他们没有超过2个或相等的员工id。我的意思是这样的,我需要显示:

如何进行查询?我使用了这个查询,但它不起作用。还有条件where名称,如“%”。

SELECT COUNT(id_employee), name 
FROM employees
WHERE name LIKE '%' AND id_employee NOT IN
(SELECT employee_id
FROM employee_roles);
r1wp621o

r1wp621o1#

如果希望员工只担任一个角色,则可以使用聚合:

select id_employee
from employee_roles
group by id_employee
having count(*) = 1;

如果希望员工具有0或1个角色,则需要使用 left join :

select e.id_employee, e.name
from employees e left join
     employee_roles er
     on e.id_employee = er.id_employee
group by e.id_employee, e.name
having count(er.id_employee) <= 1;

如果要对它们进行计数,请使用子查询:

select count(*)
from (select e.id_employee, e.name
      from employees e left join
           employee_roles er
           on e.id_employee = er.id_employee
      group by e.id_employee, e.name
      having count(er.id_employee) <= 1
     ) e
ghhkc1vu

ghhkc1vu2#

请尝试以下操作
第一个选项使用 left join ```
select
name
from
(
select
id_employee,
name
from employees e
left join employee_roles er
on e.id_employee = er.employee_id
group by
id_employee,
name
having count(employee_id) <= 1
) val

第二个选项usin `union all` ```
select
    name
from employees e
where not exists (
    select 
        employee_id
    from employee_roles er
    where e.id_employee = er.employee_id
)

union all

select
    name
from employee_roles er
join employees e
on e.id_employee = er.employee_id
group by 
    name
having count(employee_id) = 1

输出:

| name  |
| ----- |
| Poul  |
| Erick |
| Joy   |
| Smith |
w6lpcovy

w6lpcovy3#

您需要加入表,然后使用 COUNT(*) 以及 GROUP BY . 然后你可以检查一下计数是否正确 1 筛选具有多个角色的员工。

SELECT name
FROM employees AS e
JOIN employee_roles AS r ON e.id_employee = r.id_employee
GROUP BY e.id_employee
HAVING COUNT(*) = 1

相关问题