(我的)SQL:从唯一的人中选择日志文件中的20个最新条目

时间:2010-08-24 09:27:43

标签: sql mysql

我有一个日志文件,记录来自各种表的插入/删除/更新。 我想概述最近的20个人记录了哪里更新,按上次更新日期时间DESC排序

我现在拥有的是:

SELECT DISTINCT logfile.idvalue, DATE_FORMAT(logfile.logDateTime,'%d-%m-%Y  %H:%i') AS thedatetime, CONCAT_WS(' ',people.peopleSurname,people.peopleLastname) AS peopleName
FROM logfile,people
WHERE 0=0
AND logfile.tablename='people'
AND logfile.action='update'
AND logfile.idvalue=people.peopleID
GROUP BY logfile.idvalue
ORDER BY logfile.logDateTime DESC,logfile.idvalue DESC

但这会导致logDateTimes与最新(Max)“update-entry”的日期时间不对应 我错过了什么?!

感谢 巴特

3 个答案:

答案 0 :(得分:2)

SELECT  *
FROM    logfile lf
WHERE   tablename = 'people'
        AND action = 'update'
        AND logdatetime = 
        (
        SELECT  MAX(logdatetime)
        FROM    logfile lfi
        WHERE   lfi.idvalue = lf.idvalue
                AND lfi.tablename = lf.tablename
                AND lfi.action = lf.action
        )
ORDER BY
        logdatetime DESC
LIMIT 20

创建以下索引:

(tablename, action, idvalue, logdatetime)
(tablename, action, logdatetime)

让它快速工作。

答案 1 :(得分:1)

也许这可能有用......

SELECT *
    FROM (SELECT MAX(logdatetime) AS latest_time,
                 idvalue          AS idvalue
              FROM logfile
              WHERE tablename = 'people' AND
                    action    = 'update'
              GROUP BY idvalue) AS max_times
    ORDER BY latest_time DESC
    LIMIT 20;

答案 2 :(得分:1)

<强>问题

如果您在同一查询中选择logDateTime,您将获得该人更新该表的每个日期时间的结果,即每人多个结果。

<强>解决方案

而是使用MAX为该用户选择最新的日期时间。您也可以使用别名按MAX值排序。

经过测试和运行的代码(没有子查询!)

SELECT DISTINCT 
l.idvalue, 
CONCAT_WS(' ',p.peopleSurname,p.peopleLastname) AS peopleName,
DATE_FORMAT(MAX(l.logDateTime),'%d-%m-%Y  %H:%i') as thedatetime
FROM 
logfile l INNER JOIN people p ON l.idvalue = p.peopleID
WHERE
l.tablename='people' AND l.action='update'
GROUP BY 
l.idvalue, p.peopleSurname, p.peopleLastname
ORDER BY 
thedatetime DESC, l.idvalue DESC
LIMIT 0, 20;

我已经使用table作为people和logfile的别名,使其更容易阅读并切换到更常见的连接语法。