gpt4 book ai didi

MySQL SELECT with IF 基于时间戳

转载 作者:行者123 更新时间:2023-11-29 05:59:03 27 4
gpt4 key购买 nike

我有一个 MySQL 数据库,其中包含 3 个表,定义如下。

Readings: (_id, value, timestamp, sensorId)
Sensor: (_id)
DeviceSensor: (deviceId, sensorId, timestamp)

每个Reading 都有收集数据的时间戳。 SensorReading 的所有者。 DeviceSensor 包含 DeviceSensor 之间的关系,包括关系开始时间的时间戳。

在我的架构中,当 DeviceSensor 配对时,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 介于 14835279321507058076 之间的 Readings 应该返回 sensorId = 11507058076 之后的 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 中选择记录,这些记录用于主选择的当前传感器,仅限于那些与读取时间戳配对的记录。 LIMITORDER BY ds.timestamp DESC 一起选择最新的。

关于MySQL SELECT with IF 基于时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com