【问题标题】:Find the position of a string match查找字符串匹配的位置
【发布时间】:2021-04-04 09:35:16
【问题描述】:

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

name
abc def ghi
lmnop qrst uvw
xyz

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

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

并且匹配的位置应该是 5。 如何找到比赛的位置?

【问题讨论】:

    标签: sql postgresql pattern-matching


    【解决方案1】:
    select name, position('ef', name)
    from your_table
    where position('ef', name) > 0
    

    【讨论】:

      【解决方案2】:

      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”。 大表的性能差异很大。

      关于那个三元组索引:

      【讨论】:

        猜你喜欢
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 2019-02-21
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 2012-12-24
        相关资源
        最近更新 更多