我目前正在尝试优化MySQL语句。它需要大约10秒并输出两个整数的平均差。事件表包含6个cols,并由它的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 |
+----+-------------+------------+------+-----------------------------------------------------+-------------+---------+-------------+--------+-----------------------+
答案 0 :(得分:3)
一种方法是按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