I have a table that holds readings of various meters
+-----------+---------+---------+---------+---------------------+
| 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 |
+-----------+---------+---------+---------+---------------------+
In my application I need to have available both the current reading (which may or may not be present) and the previous reading which may be from a few months back. So I may have the present reading in July, but the previous reading could be in April.
I am using the following query to retrieve the previous reading:
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
This works decent, but I am not happy that I am using a SELECT within another SELECT as I fear as the table gets bigger and bigger the request will take longer and longer. Is there any other way to retrieve the previous reading? Or is there any way to make this query more efficient?
Or, ideally, have both the present reading and the previous one in the same query?
Thank you.