如何在MySQL中显示每个组的最新记录

时间:2018-07-04 19:48:26

标签: mysql sql database mysql-workbench

我有以下MySQL查询:

SELECT * 
FROM person person
     LEFT OUTER JOIN (employee_location employee_location
         INNER JOIN location_status location_status
             ON  employee_location.type = location_status.status_id )
         ON  person.per_id = employee_location.person_id    
ORDER BY person.per_given

哪个给我以下结果:

enter image description here

我希望只能显示每个人的最新记录:

enter image description here

我是否可以通过在上面的MySQL查询中添加一些内容来做到这一点?

我的模式:

表格=列

person = per_id,per_given

employee_location = id,person_id,类型,日期时间

location_status = status_id,status_type

2 个答案:

答案 0 :(得分:1)

一种方法是相关子查询。我可以推测一下您的表是什么样的,所以我猜查询看起来像这样:

SELECT * 
FROM person p JOIN
     employee_location el
     ON el.person_id = p.per_id JOIN
     location_status ls
     ON  el.type = ls.status_id
WHERE el.date_time = (SELECT MAX(el2.date_time)
                      FROM employee_location el2
                      WHERE el2.per_id = el.per_id
                     )
ORDER BY p.per_given

答案 1 :(得分:0)

您可以使用MAX()

SELECT per_id, MAX(date_time) FROM person GROUP BY per_id;