I have two tables ‘poolTemp’ and ‘weather’. Both tables contain the columns "timeStamp" and "tempC". I want to join the tables with both "tempC" but only when poolTime.timeStamp is within 5 minutes of weather.timeStamp
poolTemp.timeStamp data is recorded up to every 5 minutes, weather.timeStamp is recorded every hour
I have the following so far, but it is not exactly returning matches…
SELECT DISTINCT poolTemp.time, poolTemp.tempC
FROM poolTemp
LEFT JOIN weather
ON TIMESTAMPDIFF(MINUTE,weather.time, poolTemp.time) < 15
I am expecting to see a table with only timestamps that are within 15 minutes of each other but I see all of the timestamps from poolTemp (a temp reading every 5 minutes).
Thanks
Sample data:
poolTemp:
time;tempC
2024-01-22 12:25:05;24.63 <-- SHOULD BE SELECTED
2024-01-22 12:20:05;24.58 <-- SHOULD BE SELECTED
2024-01-22 12:15:09;24.72
2024-01-22 12:10:05;24.58
2024-01-22 12:05:05;24.58
2024-01-22 12:00:09;24.72
2024-01-22 11:55:05;24.92
2024-01-22 11:50:04;24.59
2024-01-22 11:45:09;24.42
2024-01-22 11:40:05;24.48 <-- SHOULD BE SELECTED
2024-01-22 11:35:05;24.58 <-- SHOULD BE SELECTED
2024-01-22 11:30:09;24.58 <-- SHOULD BE SELECTED
2024-01-22 11:25:05;24.64 <-- SHOULD BE SELECTED
2024-01-22 11:20:05;24.74 <-- SHOULD BE SELECTED
2024-01-22 11:15:09;24.74
2024-01-22 11:10:05;24.53
2024-01-22 11:05:05;24.53
2024-01-22 11:00:09;24.64
2024-01-22 10:55:05;24.84
2024-01-22 10:50:05;25.24
2024-01-22 10:45:09;25.47 <-- SHOULD BE SELECTED
2024-01-22 10:40:05;25.47 <-- SHOULD BE SELECTED
2024-01-22 10:35:05;25.47 <-- SHOULD BE SELECTED
2024-01-22 10:30:09;25.36 <-- SHOULD BE SELECTED
2024-01-22 10:25:05;25.36 <-- SHOULD BE SELECTED
2024-01-22 10:20:05;25.26 <-- SHOULD BE SELECTED
weather data
time;tempC;
2024-01-22 12:34:02;10.50
2024-01-22 11:34:02;9.90
2024-01-22 10:34:02;9.09
2024-01-22 09:34:02;8.49
2024-01-22 08:34:02;8.26
2
Answers
Ended up being operator error, forgot to select from the second table. When i did this the data was correct!!
And also the insertion of ABS() to the timestampdiff() function also helped...
Now shows:
and reducing the time period to 5 minutes gives this
Your condition
TIMESTAMPDIFF(MINUTE,weather.time, poolTemp.time) < 15
matches any times inpoolTemp
that are before some time inweather
, because the difference will be negative, and all negative numbers are less than 15.Change that to
TIMESTAMPDIFF(MINUTE,weather.time, poolTemp.time) BETWEEN 0 AND 14
if you only want thepoolTemp
rows that are less than 15 minutes after aweather
rows. Or useABS()
to restrict to 15 minutes before or after.Also, use
JOIN
rather thanLEFT JOIN
so you don’t get poolTemp rows with no corresponding weather row.DEMO