你已经很接近了。试试这个:
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
order by no_of_employees asc
limit 1
例子:
create table locations (location_id int, city varchar(20));
insert into locations values (1, 'LA'), (2, 'NY');
create table departments (department_id int, location_id int);
insert into departments values (1, 1), (2, 1), (3, 2), (4, 2);
create table employees (employee_id int, department_id int);
insert into employees values (1, 1), (2, 1), (3, 1), (4, 3), (5, 4);
Result of the query:
| city | no_of_employees |
|------|-----------------|
| NY | 2 |
SQLFiddle 示例:http://sqlfiddle.com/#!9/75aa1/1
按照评论中的要求使用子查询,您可以这样做 - 但不要这样做!仅在需要时使用子查询。
select * from (
-- get list of all city and employee count here
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
) subquery1
-- compare the no of employees with min. employees from the same query
where no_of_employees = (
-- find minimum number of employees here
select min(no_of_employees) from (
-- same query as subquery1
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
) subquery2
)
Result:
| city | no_of_employees |
|------|-----------------|
| NY | 2 |
SQLFiddle 示例:http://sqlfiddle.com/#!9/75aa1/4