关于比较字段使用不同字符集导致的索引失效问题

最近遇到这么一个问题,两个表通过user_id关联

where a.user_id = b.user_id

且两个表中user_id均加了索引

table a
key (user_id)

table b
unique key (user_id)

但实际查询很慢, 约3605ms。为什么这么慢呢? 通过explain extended命令可知未走索引

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEbALL3533678
1SIMPLEarefuser_iduser_id162func1Using index condition

2 rows in set, 1 warning (0.00 sec)

查看警告

show warnings\G
  Level: Note
   Code: 1003
Message: /* select#1 */ ... where (convert(`b`.`user_id` using utf8mb4) = `a`.`user_id`)
1 row in set (0.01 sec)

可知实际的执行过程中对b表索引列使用了函数。 原来是因为字符编码格式不匹配导致索引失效

a.user_id(UTF8MB4_UNICODE_CI) = b.user_id(utf8_bin)

后面改成统一使用utf8,此时查询就很快了,约14ms, 提升了约258倍。

改成统一使用utf8后 再次执行explain

idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra
1SIMPLEaALLuser_id79
1SIMPLEbeq_refuser_iduserid122a.user_id1

参考文档

http://stackoverflow.com/ques...

http://jorgenloland.blogspot....

http://jaskey.github.io/blog/...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值