以下查询需要很长时间才能完成。我已经在 join
中包含的所有字段添加了索引,尝试将 where
条件放入 join
中,我想我会问在修改 FORCE/USE
索引之前寻求建议。看来索引应该在此连接的两侧使用。似乎仅使用 i1
。
id select_type table type possible_keys key key_len ref rows filtered Extra
1 SIMPLE a ALL i1,i2,i3 2399303 100.00 Using temporary
1 SIMPLE b ref i1,i2,i3 i1 5 db.a.bt 11996 100.00 Using where
create index i1 on obs(bt);
create index i2 on obs(st);
create index i3 on obs(bt,st);
create index i4 on obs(sid);
explain extended
select distinct b.sid
from obs a inner join obs b on a.bt = b.bt and a.st = b.st
where
a.sid != b.sid and
abs( datediff( b.sid_start_date , a.sid_expire_date ) ) < 60;
我已尝试使用上面的 ALTER TABLE
和 CREATE INDEX
向 obs
添加索引。
最佳答案
由于您没有选择表 a 中的任何列,因此最好使用存在。存在允许您在不使用连接的情况下检查您正在查找的信息是否在指定的表中。删除连接可以提高性能。我也喜欢存在,因为我认为当您几个月后返回查询时,它使查询更容易理解。
select distinct b.sid
from obs b
where exists (Select 1
From obs a
Where a.bt = b.bt
and a.st = b.st
and a.sid != b.sid
and abs( datediff( b.sid_start_date , a.sid_expire_date ) ) < 60);
关于mysql - 优化mysql中的自连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24191399/