查询运行太慢甚至停止,因为超过 17000 行的时间
Query runs too slow and even it stops because exceded of time with 17000 rows
我有 table 1:
historial_id
timestamp
address
value
insertion_time
1
2022-01-29
1
84
2022-01-31
2
2022-01-29
2
40
2022-01-31
3
2022-01-30
1
84
2022-01-31
4
2022-01-30
2
41
2022-01-31
5
2022-01-30
2
41
2022-01-31
(有时会重复行)
...
我需要一个查询来获取:
timestamp
value(address 1)
value(address 2)
2022-01-29
84
40
2022-01-30
84
41
......
我试过:
SELECT timestamp, ( SELECT value
FROM historical
WHERE register_type=11
AND address=2
AND timestamp=t1.timestamp
GROUP BY value
) AS CORRIENTE_mA,
( SELECT value
FROM historical
WHERE register_type=11
AND address=1
AND timestamp=t1.timestamp
GROUP BY value ) AS Q_M3pH
FROM historical AS t1
GROUP BY timestamp;
但是太慢了,甚至因为超时而停止
我也试过 distinct
而不是 group by
我认为你需要 dynamic pivot
。
请尽量避免像 timestamp
.
这样的 MySQL reserved words
下面查询 return 只有地址 1 和 2 按时间戳分组的最大值。
这是您查询的简化版本:
select
`timestamp`
, max(case when address=1 then value end) as value_address1
, max(case when address=2 then value end) as value_address2
from historical
group by `timestamp`;
Result:
timestamp value_address1 value_address2
2022-01-29 84 40
2022-01-30 84 41
我有 table 1:
historial_id | timestamp | address | value | insertion_time |
---|---|---|---|---|
1 | 2022-01-29 | 1 | 84 | 2022-01-31 |
2 | 2022-01-29 | 2 | 40 | 2022-01-31 |
3 | 2022-01-30 | 1 | 84 | 2022-01-31 |
4 | 2022-01-30 | 2 | 41 | 2022-01-31 |
5 | 2022-01-30 | 2 | 41 | 2022-01-31 |
(有时会重复行)
...
我需要一个查询来获取:
timestamp | value(address 1) | value(address 2) |
---|---|---|
2022-01-29 | 84 | 40 |
2022-01-30 | 84 | 41 |
......
我试过:
SELECT timestamp, ( SELECT value
FROM historical
WHERE register_type=11
AND address=2
AND timestamp=t1.timestamp
GROUP BY value
) AS CORRIENTE_mA,
( SELECT value
FROM historical
WHERE register_type=11
AND address=1
AND timestamp=t1.timestamp
GROUP BY value ) AS Q_M3pH
FROM historical AS t1
GROUP BY timestamp;
但是太慢了,甚至因为超时而停止
我也试过 distinct
而不是 group by
我认为你需要 dynamic pivot
。
请尽量避免像 timestamp
.
下面查询 return 只有地址 1 和 2 按时间戳分组的最大值。
这是您查询的简化版本:
select
`timestamp`
, max(case when address=1 then value end) as value_address1
, max(case when address=2 then value end) as value_address2
from historical
group by `timestamp`;
Result:
timestamp value_address1 value_address2 2022-01-29 84 40 2022-01-30 84 41