簡體   English   中英

在mysql中優化自我連接

[英]Optimizing self join in mysql

以下查詢將永遠完成。 我已經在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 TABLECREATE 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM