postgresql 9.6 建立多列索引测试
建立测试表结构
CREATE TABLE t_test
(
id integer,
name text COLLATE pg_catalog."default",
address character varying(500) COLLATE pg_catalog."default"
);
插入测试数据
insert into t_test SELECT generate_series(1,10000000) as key, 'name'||(random()*(10^3))::integer, 'ChangAn Street NO'||(random()*(10^3))::integer;
建立3列索引
create index idx_t_test_id_name_address on t_test(id,name,address);
1.以下查询语句可以使用索引且较快
索引第一列在where语句,与条件次序无关
一般3毫秒多出结果
explain analyze select * from t_test where id < 2000 and name like 'name%' and address like 'ChangAn%';
explain analyze select * from t_test where address like 'ChangAn%' and name like 'name%' and id < 2000 ;
explain analyze select * from t_test where name like 'name%' and id < 2000 and address like 'ChangAn%' ;
explain analyze select * from t_test where id < 2000
explain analyze select * from t_test where name like 'name%' and id < 2000
explain analyze select * from t_test where address like 'ChangAn%' and id < 2000 ;
explain analyze select * from t_test where address like 'ChangAn%' and name like 'name%' and id < 2000 ;
2.以下可以使用索引,但是查询速度较慢
索引第一列在order by
explain analyze select * from t_test where address like 'ChangAn%' and name like 'name%' order by id;
17S
explain analyze select * from t_test where address like 'ChangAn%' order by id;
8s
explain analyze select * from t_test where name like 'name%' order by id;
9s
以下语句无法使用索引,索引第一列不在 where 或者 order by
explain analyze select * from t_test where address like 'ChangAn%' and name like 'name%';
explain analyze select * from t_test where address like 'ChangAn%';
explain analyze select * from t_test where name like 'name%';
建立双列索引
create index idx_t_test_name_address on t_test(name,address);
以下语句会使用索引
explain analyze select * from t_test where name = 'name580';
explain analyze select * from t_test where address like 'ChangAn%' and name like 'name580';
explain analyze select * from t_test where address like 'ChangAn%' and name = 'name580';
下面语句不会使用索引
explain analyze select * from t_test where name like 'name%'
explain analyze select * from t_test where address like 'ChangAn%'
explain analyze select * from t_test where address = 'ChangAn Street NO416'
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341