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

vaj7vani  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(288)

我有以下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

结果如下:

我只想显示每个人的最新记录:

我能通过向上面的mysql查询添加一些东西来做到这一点吗?
我的架构:
表=列
人员=每个id,每个给定的
employee\u location=id,person\u id,type,date\u time
location\u status=状态标识,状态类型

gkl3eglg

gkl3eglg1#

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

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
mrphzbgm

mrphzbgm2#

你可以用 MAX() :

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

相关问题