使用group by从连接表中获取最大日期

时间:2016-07-23 14:16:41

标签: mysql group-by max

我有3个表格 - entryrecordemployeeemployee_entryrecord(链接表)。

我喜欢的查询是为每位员工返回最新的(max timeinout记录。

employee
id employee
1  John
2  Tom

entryrecord
id created_date       inout
1 2016-07-22 16:01:38 1
2 2016-07-22 16:03:22 1
3 2016-07-22 16:05:22 2
4 2016-07-22 16:07:22 2
5 2016-07-22 16:09:22 1


I'd like the follow output
created_date         employee  inout  entryrecordid
2016-07-22 16:09:22  John       1       5
2016-07-22 16:05:22  Tom        2       3

但是,在下面的sqlfiddle中,您可以看到它没有返回正确的inoutentryrecordid值。

我已经创建了一个sqlfiddle来查看我已经完成的工作。

SQL Fiddle

任何帮助都会很棒。 感谢。

2 个答案:

答案 0 :(得分:1)

请试一试:

SELECT
finalALias.created_date,
E.employee,
finalALias.inout,
finalALias.id AS entryrecordid
FROM employee E

INNER JOIN 
(
    SELECT 
    *
    FROM entryrecord entryR 
    INNER JOIN 
    (
        SELECT
          EER.employeeid,
          MAX(created_date) max_time
        FROM entryrecord ER
        INNER JOIN employee_entryrecord EER ON ER.id = EER.entryrecordid
        GROUP BY EER.employeeid
    ) t 
    ON t.max_time=entryR.created_date
) AS finalALias
ON E.id = finalALias.employeeid
ORDER BY finalALias.created_date DESC;

WORKING DEMO

只是一个温和的提醒:

E -> employee

ER -> entryrecord

ERR -> employee_entryrecord

答案 1 :(得分:1)

问题是分组在订购之前发生。您将不得不进行子查询。您总是希望尽量减少子查询,因为它们会给SQL服务器带来沉重的负担。

我将LEFT JOINS更改为INNER JOINS,因为看起来您只想获得其他表中的员工。

SELECT 
    entryrecord.created_date, 
    employee.employee, 
    entryrecord.inout,
    entryrecord.id 
FROM 
    entryrecord 
INNER JOIN 
    employee_entryrecord ON entryrecord.id = employee_entryrecord.entryrecordid 
INNER JOIN 
    employee ON employee_entryrecord.employeeid = employee.id 
WHERE 
    entryrecord.inout in (1,2) 
    AND entryrecord.id = (
        SELECT er2.id 
        FROM employee_entryrecord eer2, entryrecord er2 
        WHERE eer2.employeeid = employee.id 
        AND er2.id = eer2.entryrecordid 
        ORDER BY er2.created_date DESC LIMIT 1
    )