MySQL Slow double join

时间:2012-01-18 17:50:17

标签: mysql performance join indexing

我有一个包含from_uidto_uid的链接表(都已编入索引),我想过滤掉某些ID。所以我这样做:

SELECT l.uid
  FROM Link l 
  JOIN filter_ids t1 ON l.from_uid = t1.id 
  JOIN filter_ids t2 ON l.to_uid   = t2.id

现在由于某种原因,这出乎意料地缓慢:(而每个单独的加入都非常快。它能否正确使用索引?

EXPLAIN告诉我:

id  select  table type  possible_keys   key      key_len ref  rows  Extra
1   SIMPLE  t1    index Null            PRIMARY  34      Null 12205 Using index
1   SIMPLE  l     ref   from_uid,to_uid from_uid 96      func 6     Using where
1   SIMPLE  t2    index Null            PRIMARY  34      Null 12205 Using where; Using index; Using join buffer

2 个答案:

答案 0 :(得分:0)

不知道它是否有所帮助,但尝试:

select l.uid
from Link l
where l.from_uid in (select id from filter_ids)
and l.to_uid in (select id from filter_ids)

也许它可以更好地使用索引。

答案 1 :(得分:0)

EXPLAIN告诉您JOIN实际上是从t1表开始的。那就是你需要在Link上添加一个新索引(或者更好地扩展当前的from_uid索引):

(from_uid, to_uid, uid)

或如果uid是主键,只需:

(from_uid, to_uid)

<强> UPD 你所描述的是奇怪的。您可以尝试运行:

SELECT STRAIGHT_JOIN l.uid
FROM Link l 
JOIN filter_ids t1 ON l.from_uid = t1.id 
JOIN filter_ids t2 ON l.to_uid   = t2.id