我创建一个带有带有唯一键的文本列的表:
create table a(id int auto_increment key,a text unique);
当我运行
show create table a;
时,它说唯一键正在使用哈希:
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a` text DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `a` (`a`) USING HASH
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
我期望的是,当我
insert into a (a)values('a');
然后select * from a where a='a';
时,它应该使用该键进行搜索。然而似乎并非如此,在大型数据集上查询速度很慢,并且 explain select * from a where a='a';
产生以下结果:
+------+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | a | ALL | a | NULL | NULL | NULL | 1 | Using where |
+------+-------------+-------+------+---------------+------+---------+------+------+-------------+
为什么 MariaDB 不使用该键进行搜索?
当我手动添加另一个键时
alter table a add key b(a) using hash;
,它按预期工作,只是一个警告Specified key was too long; max key length is 3072 bytes
。
根据 MDEV-13445,MariaDB 优化器尚不支持在文本类型上使用 HASH 索引。
另请参阅MDEV-31072。