mysql - 优化mysql中的自连接

标签 mysql sql

以下查询需要很长时间才能完成。我已经在 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 INDEXobs 添加索引。

最佳答案

由于您没有选择表 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/

相关文章:

mysql - 你应该在变化的状态列上使用 MySQL 分区吗?

mysql - 如何在 Memcached mysql cluster 7.2.2 中更改 TAB 默认值列分隔符?

python - Odoo E8103 : SQL injection risk. 如果可以,请使用参数

PHP 和 mySQL 单引号还是双引号?

sql - 需要图书馆数据库中最近 30 天的数据

php - 如何让 PHP 打印来自 MySQL 数据库的评论数

mysql - SQL只选择具有相同列值的行

c# - 当向数据库表中添加更多列时,如何让 datagridview 显示更改?

mysql - 将 SQL 查询从一个条件更改为多个条件

mysql - 使用 sql 将一些列值放入新列中