mysql 索引太长_MySQL:对太长而无法建立索引的列的有效查询

bd96500e110b49cbb3cd949968f18be7.png

In my MySQL database, I have a string column (for example, an SHA hash) which grows too long to put an index on. How can I run efficient queries against this column?

I can put an index on the first N characters of the column, but then what does the query that makes use of this "partial" index look like?

I could create a second column with N characters and put a full index on that, as a surrogate for a "partial" index. I would then query, get one or more records, and do the final step of the filtering in memory.

I can use full text search functions, but then I need to use MyISAM. MyISAM does not support ACIDity, therefore no thank you.

What is a proper way to achieve this in MySQL?

The question is not about reducing the size of my column or reconfiguring my database if it's configured with a too short key length. It's about leveraging a partial index or something of the kind painlessly, preferably without putting a burden on the application or popping up additional columns.

In my particular case, I am looking for a composite key on two columns in a UTF8 table:

create table fingerprinted_item (

type varchar (512) not null,

fingerprint varchar (512) not null,

primary key (fingerprint, type)

);

-- Then there may be a child table.

MySQL says:

[42000][1071] Specified key was too long; max key length is 767 bytes

On a different server, the max key length is 1000 bytes.

解决方案

The real issue is probably to use VARCHAR for the fingerprint column. When using the utf8 character encoding, MySQL enforces the "worst case scenario" and counts 3 bytes per character.

Either change that to 1-byte encoding (say Latin1), or use the VARBINARY type instead:

create table fingerprinted_entry

( type varchar (128) not null,

fingerprint varbinary (512) not null,

PRIMARY KEY(type, fingerprint)) ENGINE InnoDB; -- no error here

If you have to go beyond the 767 byte limit per prefix, you will have to explicitly state that when you create the index:

create table fingerprinted_entry

( type varchar (128) not null,

fingerprint varbinary (2048) not null, -- 2048 bytes

PRIMARY KEY(type, fingerprint(767))) ENGINE InnoDB; -- only the first 767 bytes of fingerprint are stored in the index

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值