MySQL查询以查找每个部门中最年轻员工的姓名和年龄

时间:2013-03-20 17:43:33

标签: mysql database

鉴于此架构:

Emp(eid: integer,ename: string,age: integer,salary: real)
Works(eid:integer,did: integer,pct_time: integer)
Dept(did:integer,budget: real,managerid:integer)

我想出了这个:

SELECT w.did, MIN(e.age) AS Youngest
FROM Works w INNER JOIN Emp e USING (eid)
GROUP BY w.did

列出了每个部门最年轻的年龄。但是,我无法弄清楚如何获得具有所列年龄的每个人的名字。我不能只将ename添加到此查询中的SELECT列表中,因为它会返回错误的名称。

我刚试过这样的东西,但它不起作用。

SELECT e2.ename, e2.age, w2.did
FROM Emp e2 INNER JOIN Works w2 USING (eid),
    (
    SELECT w.did, MIN(e.age) AS Youngest
    FROM Works w INNER JOIN Emp e USING (eid)
    GROUP BY w.did
    ) MyTable
WHERE e2.eid = eid AND e2.age = Youngest

它列出了同一部门的多个人。

4 个答案:

答案 0 :(得分:0)

这应该这样做。您需要创建一个具有did和minimum年龄的子查询,然后使用它来加入现有的emp表

SELECT w.did, ename, e.age AS Youngest
FROM Works w 
    INNER JOIN (SELECT did, MIN(age) minage
            FROM emp e INNER JOIN works w ON e.eid = w.eid
            GROUP BY did) ea
    INNER JOIN Emp e ON w.did = ea.did AND e.age = ea.minage

答案 1 :(得分:0)

尝试:

SELECT e2.ename, e2.age, w2.did
FROM Emp e2 
JOIN Works w2 USING (eid)
JOIN (SELECT w.did, MIN(e.age) AS Youngest
      FROM Works w 
      INNER JOIN Emp e USING (eid)
      GROUP BY w.did) sq
  ON w2.did = sq.did and e2.age = sq.Youngest

答案 2 :(得分:0)

尝试此操作以显示每个本地的最年轻员工:

select p.Nativeplace, p.Name, p.Dobirth from personal p having p.Dobirth=(select max(Dobirth) from personal p2 where p.Nativeplace=p2.Nativeplace group by p2.Nativeplace);

答案 3 :(得分:0)

我认为这会奏效:

SELECT e1.ename, e1.age, FROM Emp as e1, (SELECT eid, MinAge.did, MinAge.minage FROM Works, (SELECT did, MIN(age) as minage FROM Emp, Works where Emp.eid = Works.eid GROUP BY did) as MinAge WHERE Works.did = MinAge.did) as temp WHERE e1.eid = temp.eid AND e1.age = temp.minage;