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

How to get MIN/MAX with subquery

我有三个这样的表

员工

employee_ID(Pk) | department_ID(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 function.I 试过了但无法弄清楚。 有任何想法吗? 非常感谢!

你们非常接近。试试这个:

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