我目前正在尝试优化MySQL语句。大约需要 10 秒,输出两个整数的平均差。事件表包含 6 列,并按其 id 以及 run_id + 每个其他键进行索引。
该表包含 run_id 37 的 3308000 行,总共 4162050 行。 大多数连接似乎都需要时间,所以也许有一种方法可以加快速度。
send.element_id和recv.element_id是唯一的,有没有办法在sql中表达它可能会带来更好的性能?
|-------------------
|Spalte Typ
|-------------------
|run_id int(11)
|element_id int(11)
|event_id int(11) PRIMARY
|event_time int(11)
|event_type varchar(20)
|event_data varchar(20)
查询:
select avg(recv.event_time-send.event_time)
from
(
select element_id, event_time
from event
where run_id = 37 and event_type='SEND_FLIT'
) send,
(
select element_id, event_time
from event
where run_id = 37 and event_type='RECV_FLIT'
) recv
where recv.element_id = send.element_id
查询的解释:
+----+-------------+------------+------+-----------------------------------------------------+-------------+---------+-------------+--------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra |
+----+-------------+------------+------+-----------------------------------------------------+-------------+---------+-------------+--------+-----------------------+
| 1 | PRIMARY | <derived3> | ALL | NULL | NULL | NULL | NULL | 499458 | NULL |
| 1 | PRIMARY | <derived2> | ref | <auto_key0> | <auto_key0> | 4 | element_id | 10 | NULL |
| 3 | DERIVED | event | ref | run_id,run_id_2,run_id_3,run_id_4,run_id_5,run_id_6 | run_id_5 | 26 | const,const | 499458 | Using index condition |
| 2 | DERIVED | event | ref | run_id,run_id_2,run_id_3,run_id_4,run_id_5,run_id_6 | run_id_5 | 26 | const,const | 562556 | Using index condition |
+----+-------------+------------+------+-----------------------------------------------------+-------------+---------+-------------+--------+-----------------------+
最佳答案
一种方法是按 element_id 分组并使用 sum
来确定差异,然后您可以将其传递给 avg
。
select avg(diff) from (
select
sum(case when event_type = 'SEND_FLIT' then -1 * event_time else event_time end)
as diff
from event
where run_id = 37
and event_type in ('SEND_FLIT','RECV_FLIT')
group by element_id
) t
关于MySQL:优化连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35760328/