查找字符串匹配的位置

问题描述

我在 Postgres 中有一个专栏,例如:

name
abc def ghi
lmnop qrst uvw
xyz

有什么办法可以得到比赛和比赛的位置吗?
例如
如果我搜索“ef”,那么我应该使用如下查询获得第一个

select * from table where name like '%ef%';

并且匹配的位置应该是5。 我怎样才能找到比赛的位置?

解决方法

Postgres position() 函数的确切语法是,quoting the manual

position ( substring text IN string text ) → integer

使用 IN 关键字。

要获得索引支持,我建议:

SELECT *,position('ef' IN name)
FROM   tbl
WHERE  name ~ 'ef';

name ~ 'ef' od name LIKE '%ef%' 可以在 (name) 上使用三元索引,这与表达式 position('ef' IN name) > 0 不同,它不是“sargable”。 大表的性能差异。

关于那个三元组索引:

,
select name,position('ef',name)
from your_table
where position('ef',name) > 0