Mysql

選擇最年輕的記錄

  • August 12, 2019

我有一個 MariaDB 表“mdata”,其架構如下:

+-----+-----------+---------------------+------+
| id   | room      | date                | temp |
+------+-----------+---------------------+------+
| 1    | a2        | 2019-08-09 11:04:30 | 34.0 |
| 2    | a4_01     | 2019-08-09 11:04:30 | 32.0 |
| 3    | a3        | 2019-08-09 11:04:32 | 0.0  |
| 4    | a1_4      | 2019-08-09 11:04:32 | 27.0 |
| 5    | a2        | 2019-08-09 11:09:30 | 33.0 |
| 6    | a4_01     | 2019-08-09 11:09:30 | 34.0 |
| 7    | a3        | 2019-08-09 11:09:32 | 0.0  |
| 8    | a1_4      | 2019-08-09 11:09:32 | 29.0 |
+------+-----------+---------------------+------+

每 5 分鐘將新的溫度值寫入數據庫。

我不想覆蓋舊值,因為稍後會實施時間表。現在我創建了一個 Web 界面來顯示最年輕的值。

目前我正在努力尋找正確的 SELECT 查詢。

重要的是查詢的輸出與表中的順序相同,因為它被放入一個數組並進一步處理。


我試過這樣的事情:

SELECT * 
FROM mdata
WHERE temp IN
(SELECT temp FROM mdata WHERE date = (SELECT MAX(date) FROM mdata))

您需要“目前”數據和“歷史”數據。所以有兩張桌子。每次獲取新數據時INSERT INTO Historical ...INSERT INTO目前.. ON DUPLICATE KEY ..

儘管這可能不那麼優雅(由於有冗餘數據),但它使事情變得SELECTs簡單了很多。

WITH cte AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY room ORDER BY `date` DESC) rn
            FROM mdata)
SELECT id,room,`date`,`temp`
FROM cte
WHERE rn=1

如果表包含大量數據,您可以稍微限制掃描記錄的數量:

WITH 
cte1 AS (SELECT room, MAX(`date`) `date`
        FROM mdata
        GROUP BY room),
cte2 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY room ORDER BY `date` DESC) rn
        FROM mdata
        WHERE `date` >= (SELECT MIN(`date`)
                         FROM cte1))
SELECT id,room,`date`,`temp`
FROM cte2
WHERE rn=1

引用自:https://dba.stackexchange.com/questions/245113