I have three MySQL queries, how to join it to one to get result faster? Is it possible to do it with single query and if it then if it was faster than separate three queries? (I can have up to 1.5M records in table - measurements from 3 month period)
id
- auto increment, intphase
- tinyint, could be only 1,2 or 3time
- datetime, time is same for each phase group 1,2,3voltage
- float
Sample data:
+----+---------------------+-------+---------+
| id | time | phase | voltage |
+----+---------------------+-------+---------+
| 1 | 2021-01-31 19:55:01 | 1 | 235.77 |
| 2 | 2021-01-31 19:55:01 | 2 | 237.94 |
| 3 | 2021-01-31 19:55:01 | 3 | 224.63 |
| 4 | 2021-01-31 19:55:06 | 1 | 236.41 |
| 5 | 2021-01-31 19:55:06 | 2 | 238.17 |
| 6 | 2021-01-31 19:55:06 | 3 | 224.61 |
| 7 | 2021-01-31 19:55:11 | 1 | 236.45 |
| 8 | 2021-01-31 19:55:11 | 2 | 237.87 |
| 9 | 2021-01-31 19:55:11 | 3 | 223.4 |
+----+---------------------+-------+---------+
Query #1:
SELECT time, voltage AS L1
FROM measurements
WHERE phase = 1
ORDER BY id
Query #2:
SELECT time, voltage AS L2
FROM measurements
WHERE phase = 2
ORDER BY id
Query #3:
SELECT time, voltage AS L3
FROM measurements
WHERE phase = 3
ORDER BY id
Result after should be like that:
+----+---------------------+--------+--------+--------+
| id | time | L1 | L2 | L3 |
+----+---------------------+--------+--------+--------+
| 1 | 2021-01-31 19:55:01 | 235.77 | 237.94 | 224.63 |
| 2 | 2021-01-31 19:55:06 | 236.41 | 238.17 | 224.61 |
| 3 | 2021-01-31 19:55:11 | 236.45 | 237.87 | 223.4 |
+----+---------------------+--------+--------+--------+
EDIT: after all, I got a query:
SELECT
time,
GROUP_CONCAT(IF(phase = 1, voltage, NULL)) AS 'L1',
GROUP_CONCAT(IF(phase = 2, voltage, NULL)) AS 'L2',
GROUP_CONCAT(IF(phase = 3, voltage, NULL)) AS 'L3'
FROM
`measurements`
GROUP BY
time
and now results looks like:
+---------------------+--------------------+--------------------+--------------------+
| time | L1 | L2 | L3 |
+---------------------+--------------------+--------------------+--------------------+
| 2021-01-31 19:55:01 | 235.77000427246094 | 237.94000244140625 | 224.6300048828125 |
| 2021-01-31 19:55:06 | 236.41000366210938 | 238.1699981689453 | 224.61000061035156 |
| 2021-01-31 19:55:11 | 236.4499969482422 | 237.8699951171875 | 223.39999389648438 |
+---------------------+--------------------+--------------------+--------------------+
Why now voltage values are so inaccurate, all voltage stored values are with max 2 number after decimal point I don't do any math in query... then why got this strange values?