[英]MySQL SELECT with IF based on timestamp
I have a MySQL database with 3 tables as defined below. 我有一个3个表的MySQL数据库,定义如下。
Readings: (_id, value, timestamp, sensorId)
Sensor: (_id)
DeviceSensor: (deviceId, sensorId, timestamp)
Each Reading
has a timestamp of when the data was collected. 每个Reading
都有收集数据的时间戳。 The Sensor
is the owner of the Reading
. Sensor
是Reading
的所有者。 DeviceSensor
contains the relationship between Device
and Sensor
, including the timestamp of when the relationship started. DeviceSensor
包含Device
和Sensor
之间的关系,包括关系开始的时间戳。
In my architecture, when a Device
is paired with a Sensor
, the Sensor
ignores former Devices
. 在我的体系结构中,将Device
与Sensor
配对时, Sensor
忽略以前的Devices
。
What I need is to query all the Readings
and associate them with the corresponding Device
at each time of reading. 我需要的是查询所有Readings
并在每次阅读时将它们与相应的Device
关联。 For example: 例如:
DeviceSensor = [(1,1,1483527932),(1,2,1507058076)]
Sensor = [(1)]
Readings = [(1,5,1483527932,1),(2,3,1493527932,1),(3,7,1507058076,1)]
With this data, my query would return: [(1,5,1483527932,1),(2,3,1493527932,1),(3,7,1507058076,2)]
. 使用此数据,我的查询将返回: [(1,5,1483527932,1),(2,3,1493527932,1),(3,7,1507058076,2)]
。 That is, the Readings
that have timestamp
between 1483527932
and 1507058076
should return sensorId = 1
and the Readings
after 1507058076
should return sensorId = 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
The subselect selects the records from DeviceSensor
which are for the current sensor of the main select, restricted to those with a pairing up to the reading timestamp. 子选择从DeviceSensor
选择用于主选择的当前传感器的记录,仅限于与读取时间戳配对的记录。 The LIMIT
together with ORDER BY ds.timestamp DESC
selects the latest of these. LIMIT
与ORDER BY ds.timestamp DESC
选择最新的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.