从mysql表中检索第二个最后一条记录

时间:2012-06-17 18:42:07

标签: mysql sql group-by sql-order-by

我有一张表,其中包含各种米的读数

+-----------+---------+---------+---------+---------------------+
| idReading | idMeter |  index  |  usage  | dateOfReading       |
+-----------+---------+---------+---------+---------------------+
|       671 |     189 | 884.000 | 441.000 | 2012-06-01 00:00:00 |
|       672 |     190 | 170.000 |  82.000 | 2012-06-01 00:00:00 |
|       584 |     190 |  88.000 |  88.000 | 2012-05-01 00:00:00 |
|       583 |     189 | 443.000 | 443.000 | 2012-05-01 00:00:00 |
+-----------+---------+---------+---------+---------------------+

在我的应用程序中,我需要提供当前读数(可能存在或不存在)和之前的读数,这可能是几个月前的读数。所以我可能会在七月份阅读目前的读数,但之前的读数可能是四月份。

我使用以下查询来检索上一个阅读:

SELECT * FROM (
  SELECT Reading.idMeter, Reading.usage, Reading.`Index`, Reading.dateOfReading
  FROM meterReadings AS Reading
  WHERE Reading.idMeter IN (189,190)
    AND Reading.dateOfReading < '2012-07-31'  
  ORDER BY Reading.dateOfReading DESC) AS OrderendReading
GROUP BY OrderendReading.idMeter

这很有效,但我不高兴我在另一个SELECT中使用SELECT,因为我担心随着表越来越大,请求将花费更长时间。 有没有其他方法来检索以前的阅读?或者有没有办法让这个查询更有效率?

或者,理想情况下,同一查询中是否包含当前读数和前一个读数?

谢谢。

3 个答案:

答案 0 :(得分:1)

我认为相关的子查询可以实现您的目标:

SELECT  Reading.idMeter, 
        Reading.usage, 
        Reading.`Index`, 
        Reading.dateOfReading,
        (   SELECT  mr.Usage
            FROM    MeterReadings AS mr
            WHERE   mr.idMeter = Reading.idMeter
            AND     mr.DateOfReading < Reading.DateofReading
            ORDER BY DateOfReading DESC
            LIMIT 1
        ) AS PreviousReadingUsage
FROM    meterReadings AS Reading,
WHERE   Reading.idMeter IN (189,190)
AND     Reading.dateOfReading < '2012-07-31'  
ORDER BY Reading.dateOfReading DESC

答案 1 :(得分:0)

我昨天刚刚发现了'分析函数',我很确定它们涵盖了这种类型的要求。给它一个谷歌,一些关于Youtube的教程。

答案 2 :(得分:0)

试试这个:

SELECT 
  Reading.idMeter, 
  Reading.usage, 
  Reading.`Index`,
  (Select dateOfReading from meterReading order by dateOfReading desc limit 1,1)  
FROM meterReadings AS Reading   
GROUP BY Reading.idMeter;