栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

强制MySQL在Join上使用两个索引

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

强制MySQL在Join上使用两个索引

参见MySQL文档

FORCE INDEX

JOIN survey_customer_similarity AS scs FORCE INDEX (CONSUMER_ID_1,CONSUMER_ID_2)ONcr.CONSUMER_ID=scs.CONSUMER_ID_2 AND cal.SENDER_CONSUMER_ID=scs.CONSUMER_ID_1 OR cr.CONSUMER_ID=scs.CONSUMER_ID_1 AND cal.SENDER_CONSUMER_ID=scs.CONSUMER_ID_2

正如TheScrumMeister在下面指出的那样,它是否可以同时实际使用两个索引取决于您的数据。


这是一个示例,您需要强制该表出现两次以控制查询的执行和交集。

使用它来创建一个包含100K条记录的表,其中约1K行与过滤条件匹配,

i in (2,3)
而1K行与
j in (2,3)
以下条件匹配:

drop table if exists t1;create table t1 (id int auto_increment primary key, i int, j int);create index ix_t1_on_i on t1(i);create index ix_t1_on_j on t1(j);insert into t1 (i,j) values (2,2),(2,3),(4,5),(6,6),(2,6),(2,7),(3,2);insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i*2, j*2+i from t1;insert into t1 (i,j) select i, j from t1;insert into t1 (i,j) select i, j from t1;insert into t1 (i,j) select 2, j from t1 where not j in (2,3) limit 1000;insert into t1 (i,j) select i, 3 from t1 where not i in (2,3) limit 1000;

进行时:

select t.* from t1 as t where t.i=2 and t.j=3 or t.i=3 and t.j=2

您将获得8场匹配的比赛:

+-------+------+------+| id    | i    | j    |+-------+------+------+|     7 |    3 |    2 || 28679 |    3 |    2 || 57351 |    3 |    2 || 86023 |    3 |    2 ||     2 |    2 |    3 || 28674 |    2 |    3 || 57346 |    2 |    3 || 86018 |    2 |    3 |+-------+------+------+

EXPLAIN
在上面的查询中使用以获取:

id | select_type | table | type  | possible_keys         | key        | key_len | ref  | rows | Extra1  | SIMPLE      | t     | range | ix_t1_on_i,ix_t1_on_j | ix_t1_on_j | 5       | NULL | 1012 | Using where

即使我们

FORCE INDEX
在两个索引上添加查询,
EXPLAIN
也将返回 完全相同的内容

要使其跨两个索引收集,然后相交,请使用以下命令:

select t.* from t1 as a force index(ix_t1_on_i)join t1 as b force index(ix_t1_on_j) on a.id=b.idwhere a.i=2 and b.j=3 or a.i=3 and b.j=2

使用该查询

explain
可获取:

id | select_type | table | type  | possible_keys | key        | key_len | ref  | rows | Extra1  | SIMPLE      | a     | range | ix_t1_on_i    | ix_t1_on_i | 5       | NULL | 1019 | Using where1  | SIMPLE      | b     | range | ix_t1_on_j    | ix_t1_on_j | 5       | NULL | 1012 | Using where; Using index

这证明正在使用索引。但这可能会更快,也可能不会更快,这取决于许多其他因素。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392607.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号