0

我有一张桌子 - 员工

id | staff Name | adress
-------------------------
1 | Mr.A        | Any Address
2 | Mr. B       | Any Address

第二张表 - 就业历史

eid | staff_id | school_id | type       | grade | date_of_appointmet
--------------------------------------------------------------------
1   | 1         | 1        |Promotion   | 17    | 2012-12-12
2   | 1         | 2        |promotion   | 18    | 2013-2-2
3   | 2         | 2        |appointment | 17    | 2013-3-3
 and so on tables moves

现在的问题是

  • 我想从员工表中获取该人的最新工作及其详细信息
  • 我如何计算有多少 17 年级工作人员在 school_id 1 工作(记住,staff_id 1 (mr.a) 现在已晋升为 18 岁,现在在 school_id 2 工作。)
4

2 回答 2

0

What about something like

SELECT *
FROM employment_history eh1
WHERE eh1.date_of_employment = (
    SELECT max(eh2.date_of_employment)
    FROM staff s
    JOIN employment_history eh2 ON s.id = eh2.staff_id
    WHERE s.id = ?
)

Recplacing the ?, or using bind_param() as appropriate.

于 2013-09-20T21:33:34.113 回答
0
select staff_id, max(date_of_appointment) as date_of_appointment
from employment_history
group by staff_id

此查询将返回每个 staff_id 的最新员工记录。将其转换为子查询并加入就业历史表

Select grade, count(1) 
from
(select staff_id, max(date_of_appointment) as date_of_appointment
from employment_history
group by staff_id) a
inner join employment_history e on e.staff_id = a.staff_id and a.date_of_appointment = e.date_of_appointment
 group by grade

此解决方案假设 staff_id + date_of_appointment 是一个唯一键......如果您有多个行,其中一个 staff_id 在一个日期有多个就业历史条目,这将不起作用。您需要一些逻辑来使“最近的就业历史条目”返回唯一的数据组合...如果 staff_id + max(date_of_appointment) 不是唯一的,您需要在“a”子查询中提出逻辑返回唯一数据。

于 2013-09-20T22:00:42.673 回答