BLOB或TEXT字段使用散列值和前缀索引优化提高查询速度

1.创建表,存储引擎为myisam,对大文本字段blob使用MD5函数建立一个散列值

create table t2(id varchar(60), content blob, hash_value varchar(40))engine=myisam default charset=utf8;

 

2.插入数据

insert into t2 values(1, repeat('world1', 20), md5(content));

insert into t2 values(2, repeat('world2', 40), md5(content));

insert into t2 values(3, repeat('world3', 40), md5(content));

insert into t2 values(4, repeat('world4', 70), md5(content));

insert into t2 values(5, repeat('world5', 100), md5(content));

 

3.使用散列值查询,只用于精确匹配

select * from t2 where hash_value=md5(repeat('world4', 70));

使用散列值查询比使用blob文本字段查询速度更快,因为使用散列值匹配的长度要短得多。

 

4.若要进行模糊查询,可以对blob字段的前n列做前缀索引

create index idx_blob on t2(content(150));

在t2表的字段content字段的前150字节做前缀索引

 

5.使用explain或desc查看执行计划,是否使用了索引

mysql> explain select * from t2 where content like 'world4%';

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

| id | select_type | table | type  | possible_keys | key      | key_len | ref  | rows | Extra       |

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

|  1 | SIMPLE      | t2    | range | idx_blob      | idx_blob | 153     | NULL |    1 | Using where |

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

1 row in set (0.01 sec)

mysql> desc select * from t2 where content like 'world4%';

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

| id | select_type | table | type  | possible_keys | key      | key_len | ref  | rows | Extra       |

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

|  1 | SIMPLE      | t2    | range | idx_blob      | idx_blob | 153     | NULL |    1 | Using where |

+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+

1 row in set (0.00 sec)

可以看出,使用了前缀索引idx_blob。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值