[英]MySQL SELECT with IF based on timestamp
我有一个3个表的MySQL数据库,定义如下。
Readings: (_id, value, timestamp, sensorId)
Sensor: (_id)
DeviceSensor: (deviceId, sensorId, timestamp)
每个Reading
都有收集数据的时间戳。 Sensor
是Reading
的所有者。 DeviceSensor
包含Device
和Sensor
之间的关系,包括关系开始的时间戳。
在我的体系结构中,将Device
与Sensor
配对时, Sensor
忽略以前的Devices
。
我需要的是查询所有Readings
并在每次阅读时将它们与相应的Device
关联。 例如:
DeviceSensor = [(1,1,1483527932),(1,2,1507058076)]
Sensor = [(1)]
Readings = [(1,5,1483527932,1),(2,3,1493527932,1),(3,7,1507058076,1)]
使用此数据,我的查询将返回: [(1,5,1483527932,1),(2,3,1493527932,1),(3,7,1507058076,2)]
。 也就是说, timestamp
在1483527932
和1507058076
之间的Readings
应返回sensorId = 1
,而1507058076
之后的Readings
应返回sensorId = 2
。
SELECT r._id
,r.value
,r.timestamp
,(SELECT max(ds.deviceId) as deviceId
FROM DeviceSensor as ds
WHERE ds.timestamp <= r.timestamp
AND ds.sensorId = r.sensorId
ORDER BY ds.timestamp DESC
LIMIT 1) as deviceId
FROM Readings as r
子选择从DeviceSensor
选择用于主选择的当前传感器的记录,仅限于与读取时间戳配对的记录。 LIMIT
与ORDER BY ds.timestamp DESC
选择最新的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.