I have two tables, one is for measurements and every 3 seconds or so a value is written in a very simple structure:
Measurements:
timestamp | value |
---|---|
1679474929 | 516 |
1679474933 | 501 |
1679474936 | 505 |
While the second contains all meta information, trigger values, etc. This one is changed sporadically, but randomly. Meta information is valid from the moment of change to a different change that would be sometimes a week and sometimes a month. Thousands of measurements are done between each change.
What I need is to JOIN them together in the way that all the measurements would have meta information from a relevant period in the meta table.
I’m imagining some sort of conditional comparison, something like this.
First, try:
ON measurements.timestamp=meta.timestamp
then
ON DATE_FORMAT(FROM_UNIXTIME(measurements.timestamp), '%Y-%m-%d %H:%i')=DATE_FORMAT(FROM_UNIXTIME(meta.timestamp), '%Y-%m-%d %H:%i')
then
ON DATE_FORMAT(FROM_UNIXTIME(measurements.timestamp), '%Y-%m-%d %H')=DATE_FORMAT(FROM_UNIXTIME(meta.timestamp), '%Y-%m-%d %H')
then
ON DATE_FORMAT(FROM_UNIXTIME(measurements.timestamp), '%Y-%m-%d')=DATE_FORMAT(FROM_UNIXTIME(meta.timestamp), '%Y-%m-%d')
etc. until the condition is satisfied.
Is something like this possible?
2
Answers
You could do it by using the LEAD() window function to get the value of the next
meta
row’stimestamp
:It may be worth testing the performance of the lateral derived table version of Bernd’s solution, if you want to return multiple columns from
meta
:did you mean something like this ?
** Sample **