like查询效率低下
对于相对较大的表数据查询,使用 like 会降低查询速度,各位可以试一下(仅仅是优化,目前在学习缓存)
如插入200万条数据
create table test(id int4,name text)
insert into test(id,name)
select r ,r||’_tans’ from generate_series(1,2000000)r
select * from test where name like ‘%_tans’ 耗时700多毫秒(印象里是这样,博主比较懒哈哈)
解决方案
建立索引
使用to_tsvector(‘english’,columnname)
create index tttt on test using gin(to_tsvector(‘english’,name))
走索引
select * from test where to_tsvector(‘english’,name) @@ to_tsquery(‘english’,‘1_tans’)
@@指包含 因为建立索引的时候指明了语言,所以查询的时候也要指明语言,否则不会使用索引
不走索引
select * from test where to_tsvector(name) @@ to_tsquery(‘1_tans’)