I have two tables from the same database:
Table READINGS:
Table SENSORS:
I'm trying to create a query that will return, for each sensor registered in SENSORS, it's last row registered in READINGS. Note that the same sensor can have many registers in READINGS, but ONLY ONE in SENSORS.
The result should be something like:
Dump of the database: https://dl.dropboxusercontent.com/u/85576999/redeSensores.sql
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
Or if you need info from both tables:
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
UPDATE AVG last day
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;
UPDATE 2 To filter aggregated records you can use HAVING
:
http://sqlfiddle.com/#!9/95818/11
HAVING AVG(r_avg.temperature)!=42
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.