查找字符串匹配的位置
Find the position of a string match
我在 Postgres 中有一个专栏,例如:
name
abc def ghi
lmnop qrst uvw
xyz
有什么方法可以得到匹配项和匹配项的位置吗?
例如
如果我搜索 'ef' 那么我应该使用如下查询获得第一个:
select * from table where name like '%ef%';
匹配的位置应该是5。
如何找到匹配的位置?
select name, position('ef', name)
from your_table
where position('ef', name) > 0
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”。 大 大表的性能差异。
关于那个卦标:
- PostgreSQL LIKE query performance variations
我在 Postgres 中有一个专栏,例如:
name
abc def ghi
lmnop qrst uvw
xyz
有什么方法可以得到匹配项和匹配项的位置吗?
例如
如果我搜索 'ef' 那么我应该使用如下查询获得第一个:
select * from table where name like '%ef%';
匹配的位置应该是5。 如何找到匹配的位置?
select name, position('ef', name)
from your_table
where position('ef', name) > 0
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”。 大 大表的性能差异。
关于那个卦标:
- PostgreSQL LIKE query performance variations