0

我有一张桌子,上面有各种仪表的读数

+-----------+---------+---------+---------+---------------------+
| 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 |
+-----------+---------+---------+---------+---------------------+

在我的应用程序中,我需要同时提供当前读数(可能存在也可能不存在)和可能来自几个月前的先前读数。因此,我可能在 7 月获得当前读数,但之前的读数可能在 4 月。

我正在使用以下查询来检索以前的读数:

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,因为我担心随着表变得越来越大,请求会花费越来越长的时间。有没有其他方法可以检索以前的读数?或者有什么方法可以让这个查询更有效率?

或者,理想情况下,在同一个查询中同时拥有当前阅读和前一个阅读?

谢谢你。

4

3 回答 3

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
于 2012-06-17T20:14:51.003 回答
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;
于 2012-06-17T19:08:20.653 回答
0

我昨天刚刚发现了“分析函数”,我很确定它们满足了这种类型的要求。给它一个谷歌,在 Youtube 上也有一些教程。

于 2012-06-17T18:52:27.487 回答