与连接图的其余部分断开连接

时间:2015-01-24 11:16:36

标签: sql oracle join

我的任务是查询数据库,选择在最多部门工作的人数。我做了以下事情:

select count(*) from Persons join Departments using (Department_id)
where Department_id = 
(select Department_id from Persons join Departments using (Department_id) 
 group by Department_id having count(*) = 
  (select max(count(*)) from Persons 
   join Departments using (Department_id) group by Department_id)
);

它工作正常,但我收到一个警告,即Persons与连接图的其余部分断开连接。这个解决方案有问题吗?或者它可能更容易完成?

2 个答案:

答案 0 :(得分:1)

我不是max(count(*))构造的粉丝。它是一个Oracle扩展,它改变了group by的语义(在所有其他情况下,每组返回一行)。怎么样:

with d as (
      select count(*) as cnt
      from persons
      group by department_id
     )
select *
from d
where cnt = (select max(cnt) from d);

答案 1 :(得分:0)

你是对的,连接实际上是多余的。这是我提出的新解决方案:

select count(*) from Persons
where Department_id is not null
group by Department_id
having count(*) = (select max(count(*)) from Persons
                  where Department_id is not null
                  group by Department_id);