• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MySQL 中字符串字段,在使用in时,没有加引号时的性能陷阱

mysql 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

场景和环境

redhat6.5 + 64位 + 12核心 + 16G

表数量 600w

MySQ

本文来源gao!%daima.com搞$代*!码网1

L 5.0

问题描述

在使用in过程中,同事写了一个简单的in条件查询(字段是普通索引,varchar),由于拼装sql的时候,没有使用引号,导致出现大量慢查询

问题SQL

select count(*) total from member_phone where phone in(1521xxx541,15845xxx412)

问题SQL和纠正过的写法对比

执行时间

mysql> select count(*) total from member_phone where phone in(1521xxx541,15845xxx412);+-------+| total |+-------+|     1 | +-------+1 row in set (2.76 sec)mysql> select count(*) total from member_phone where phone in('1521xxx541','15845xxx412');+-------+| total |+-------+|     1 | +-------+1 row in set (0.01 sec)mysql> select count(*) total from member_phone where (phone='1521xxx541' or phone='15845xxx412');+-------+| total |+-------+|     1 | +-------+1 row in set (0.00 sec)

EXPLAIN

mysql> explain select count(*) total from member_phone where phone in(1521xxx541,15845xxx412) \G;*************************** 1. row ***************************           id: 1  select_type: SIMPLE        table: member_phone         type: indexpossible_keys: phone          key: phone      key_len: 18          ref: NULL         rows: 6307075        Extra: Using where; Using index1 row in set (0.00 sec)mysql> explain select count(*) total from member_phone where phone in('1521xxx541','15845xxx412') \G;*************************** 1. row ***************************           id: 1  select_type: SIMPLE        table: member_phone         type: rangepossible_keys: phone          key: phone      key_len: 18          ref: NULL         rows: 2        Extra: Using where; Using index1 row in set (0.00 sec)mysql> explain select count(*) total from member_phone where (phone='1521xxx541' or phone='15845xxx412') \G;*************************** 1. row ***************************           id: 1  select_type: SIMPLE        table: member_phone         type: rangepossible_keys: phone          key: phone      key_len: 18          ref: NULL         rows: 2        Extra: Using where; Using index1 row in set (0.01 sec)

总结

在三个类型的sql中,效率从高到低分别是 or,in 添加了引号, in不加引号。在explain中看到不加引号时,显示的用上了索引phone,type 变成了 index ,和全表扫描差不多了,只不过MySQL扫描时按索引的次序进行而不是行。

提醒

在where多个or,in中条件个数比较多,或者多个in 条件时,实际性能都比较差的。以上测试我个人仅在MySQL5.0中测试,高版本官方不知是否优化过。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MySQL 中字符串字段,在使用in时,没有加引号时的性能陷阱

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址