如何使用子查询获取MIN / MAX

时间:2015-09-23 17:54:17

标签: mysql sql aggregate-functions

我有三张这样的表

员工

employee_ID(Pk)|部门标识(FK)

部门

department_ID(Pk)| LOCATION_ID(FK)

位置

location_ID(Pk)|城市

我想要的是拥有最少员工的城市的名称。 我尝试过类似下面的sql:



SELECT l.city
FROM employees e, departments d, locations l
WHERE e.department_ID = d.department_ID
AND d.location_ID = l.location_ID
GROUP BY l.city
ORDER BY 2 
LIMIT 1




但那不是一个好人。我希望它在子查询和MIN函数可能COUNT函数。我试过但但无法弄明白。 有任何想法吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

你非常接近。试试这个:

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