我有两个来自同一个数据库的表:
表传感器:
我正在尝试创建一个将返回的查询,对于在SENSORS中注册的每个传感器,它是在READINGS中注册的最后一行。请注意,同一传感器在READINGS中可以有多个寄存器,但在SENSORS中只有一个寄存器。
转储数据库:https://dl.dropboxusercontent.com/u/85576999/redeSensores.sql
答案 0 :(得分:1)
http://sqlfiddle.com/#!9/95818/5
SELECT readings.*
FROM readings
INNER JOIN sensors
ON sensors.idSensor = readings.sensorid
LEFT JOIN readings r
ON r.sensorid = readings.sensorid
AND r.`datetime` > readings.`datetime`
WHERE r.id IS NULL
或者,如果您需要来自两个表的信息:
http://sqlfiddle.com/#!9/95818/6
SELECT readings.*,
sensors.*
FROM readings
INNER JOIN sensors
ON sensors.idSensor = readings.sensorid
LEFT JOIN readings r
ON r.sensorid = readings.sensorid
AND r.`datetime` > readings.`datetime`
WHERE r.id IS NULL
更新 AVG最后一天
http://sqlfiddle.com/#!9/95818/10
SELECT t.*,
AVG(r_avg.temperature),
AVG(r_avg.pollution),
AVG(r_avg.noise),
AVG(r_avg.humidity)
FROM (SELECT readings.*, sensors.*
FROM readings
INNER JOIN sensors
ON sensors.idSensor = readings.sensorid
LEFT JOIN readings r
ON r.sensorid = readings.sensorid
AND r.`datetime` > readings.`datetime`
WHERE r.id IS NULL
) t
LEFT JOIN readings r_avg
ON t.sensorid = r_avg.sensorid
AND r_avg.`datetime` >= DATE_ADD(t.datetime,INTERVAL -1 DAY)
GROUP BY t.id;
更新2 要过滤汇总记录,您可以使用HAVING
:
http://sqlfiddle.com/#!9/95818/11
HAVING AVG(r_avg.temperature)!=42