有 2 个表:
表温度_现在:
machine_id | temperature
------------------------
1 | 15
2 | 20
3 | 13
表温度历史记录:
change_id | machine_id | temperature | controller
-------------------------------------------------
1 1 6 Carl
2 2 9 Steve
3 1 7 John
4 1 15 Peter
5 2 20 Peter
6 3 13 Martin
温度_now.machine_id = 温度_历史.machine_id
change_id 是 auto_increment
我需要获取每台机器的最后一次温度变化:
machine_id | temperature_now | temperature_before | controller
--------------------------------------------------------------
1 15 7 John
2 20 9 Steve
感谢您的帮助。
最佳答案
您可以使用通用表表达式来完成此操作,如下所示。
已更新
WITH History (MachineID, Temp, Controller)
AS
(
SELECT machine_id, temperature, controller
FROM dbo.temperature_history
WHERE change_id in ((SELECT MAX(change_id) FROM dbo.temperature_history AS TH
INNER JOIN dbo.temperature_now AS TN
ON TN.machine_id = TH.machine_id
WHERE TN.temperature != TH.temperature
GROUP BY TH.machine_id))
)
SELECT N.machine_id,
N.temperature,
H.Temp as 'temperature_before',
H.Controller
FROM dbo.temperature_now AS N
INNER JOIN History AS H
ON H.MachineID = N.machine_id
ORDER BY N.machine_id;
然后你会得到如下结果:
machine_id temperature temperature_before Controller
1 15 7 John
2 20 9 Steve
关于mysql - 在 WHERE 中加入 MAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194506/