I store sensor data in a MySQL table. The table has the fields id, timestamp, mac, temp and humidity.
Id is an unique autoincrement index, timestamp the time when the data was entered, Mac the Mac address of the sensor.
So for each sensor at each timestamp an entry is created. If all sensors are working the timestamp will be equal, but it can be that some sensors are not reachable.
I know want to query the temperatures of all sensors at all timestamps. For 3 sensors I came up with the following:
SELECT a.timestamp, a.temp, b.temp, c.temp from `data` as a
inner join data as b on a.timestamp = b.timestamp
inner join data as c on a.timestamp = c.timestamp
where a.mac = 'xx:xz:xz:34:03:F0' and
b.mac = 'xz:xx:xx:34:C6:99' and
c.mac='xx:xx:xx:32:27:36' order by a.timestamp
Sample data:
INSERT INTO `data` (`id`, `mac`, `timestamp`, `temp`, `humidity`, `battery`) VALUES
(132, '58:2D:34:32:27:36', '2020-02-01 19:30:11', '23.2', '53.5', '0.0'),
(133, '58:2D:34:34:C6:99', '2020-02-01 19:30:11', '23.1', '51.4', '0.0'),
(134, '58:2D:34:34:03:F0', '2020-02-01 19:30:11', '24.1', '50.0', '0.0'),
(138, '58:2D:34:32:27:36', '2020-02-01 19:40:08', '23.2', '54.3', '0.0'),
(139, '58:2D:34:34:C6:99', '2020-02-01 19:40:08', '23.2', '51.6', '0.0'),
(140, '58:2D:34:34:03:F0', '2020-02-01 19:40:08', '24.1', '50.1', '0.0'),
(141, '58:2D:34:32:27:36', '2020-02-01 19:50:08', '23.3', '54.6', '0.0'),
(142, '58:2D:34:34:C6:99', '2020-02-01 19:50:08', '23.2', '51.4', '0.0'),
(143, '58:2D:34:34:03:F0', '2020-02-01 19:50:08', '24.0', '50.3', '0.0');
Example output:
Timestamp. , Mac1, Mac2, Mac3
2020-02-01 19:30:08, 24.0, 23.2, 23.0
2020-02-01 19:40:08, 24.0, 23.1, 23.0
2020-02-01 19:50:12, 24.1, 23.1, 23.0
But I think there should/could be a more efficient way?
Any ideas?
Thanks
where mac in ('mac1', 'mac2', ...).