如何使用SQL语法从MySQL表中选择最近或最后一条记录

时间:2015-08-04 12:12:54

标签: mysql

如何从MySQL查询中选择最近或最后100条记录?

我在数据库中有18百万条记录。我想使用Timestamp列选择100条最新记录,但运行时间超过2分钟。

在不使用Order By的情况下查找最新记录的其他任何方式?

SELECT DISTINCT (dd.TIMESTAMP)
    ,dd.Amplitude
    ,pd.PatientId
FROM DeviceDetails dd
INNER JOIN DeviceSession ds ON ds.DeviceSessionID = dd.ByDevSessionId
INNER JOIN PatientSession ps ON ps.PatientSessionId = ds.ByPatientSessionId
INNER JOIN PatientDetails pd ON pd.PatientDetailsId = ps.ByPatientId
WHERE pd.HospitalPatientId = 'Rorys Test Ward Test Bed 2 @ 2015-07-31 18:36:41'
    AND dd.TIMESTAMP < '2015-08-04 11:53:08.962'
ORDER BY dd.TIMESTAMP
Limit 100

2 个答案:

答案 0 :(得分:0)

尝试解释以查看执行计划。或运行以下查询。

explain  SELECT DISTINCT(dd.Timestamp), dd.Amplitude , pd.PatientId   FROM DeviceDetails dd   JOIN DeviceSession ds 
     ON ds.DeviceSessionID = dd.ByDevSessionId  
     JOIN PatientSession ps ON ps.PatientSessionId = ds.ByPatientSessionId   
     JOIN PatientDetails pd ON pd.PatientDetailsId = ps.ByPatientId   
     WHERE   pd.HospitalPatientId = 'Rorys Test Ward Test Bed 2 @ 2015-07-31 18:36:41'
     AND dd.Timestamp < '2015-08-04 11:53:08.962'       
     ORDER BY dd.Timestamp   
     Limit 100 

关于解释你可以在这里看到教程。 http://www.slideshare.net/phpcodemonkey/mysql-explain-explained

答案 1 :(得分:0)

通常情况下,如果您有重复记录可以grouped,则使用某种聚合函数是个好主意。此外,您的order by语句按升序对Timestamp字段进行排序,而为了获取最新记录,您可能希望使用关键字desc明确地按降序对其进行排序。如果您的DeviceDetails表中有主键或自动递增字段,那么更好的选择就是,您也可以轻松地对该字段进行排序。但就目前而言,我会这样做:

SELECT
     dd.TIMESTAMP
    ,max(dd.Amplitude)
    ,max(pd.PatientId)
FROM DeviceDetails dd
INNER JOIN DeviceSession ds ON ds.DeviceSessionID = dd.ByDevSessionId
INNER JOIN PatientSession ps ON ps.PatientSessionId = ds.ByPatientSessionId
INNER JOIN PatientDetails pd ON pd.PatientDetailsId = ps.ByPatientId
WHERE pd.HospitalPatientId = 'Rorys Test Ward Test Bed 2 @ 2015-07-31 18:36:41'
    AND dd.TIMESTAMP < '2015-08-04 11:53:08.962'
GROUP BY dd.TIMESTAMP
ORDER BY dd.TIMESTAMP desc
Limit 100