MariaDB/MySQL without window function support.
Table DEVICE {
id int, <— Primary key
name varchar(10)
}
For every device there are many records in DATA table
Table DATA (
device_id int, <— Foreign key to DEVICE.id
value float
)
User provides some target_value.
Task: find the closest values in DATA table for every device.
DEVICE
-----------
id | name
-----------
1 | A
2 | B
3 | C
DATA
------------------------
device_id | value
------------------------
1 | 5.3
1 | 5.9
2 | 4.0
2 | 4.5
3 | 5.1
For the input target_value=5.0 the expected output is:
--------------------
id | value
---------------------
1 | 5.3
2 | 4.5
3 | 5.1
I know how to find closest value for a single device (e.g. device_id=2):
SELECT device_id, value FROM DATA
WHERE device_id=2 ORDER BY ABS(value-target_value) ASC LIMIT 1
... but I do not know how to extend it to return results for several device_id's