php mysql根据多个条件获取最新记录并计算它们

时间:2013-09-20 21:17:56

标签: php mysql sql

我有一张桌子 - 工作人员

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

2nd Table - employment_history

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名年级员工中有多少人在学校工作_ 1 (记住staff_id 1(mr.a)现在已升级到18,现在在school_id 2中工作。)

2 个答案:

答案 0 :(得分:0)

这样的东西
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 = ?
)

根据需要更换?或使用bind_param()

答案 1 :(得分: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'子查询中提出逻辑返回唯一数据。