PostgreSQL 匹配字符串前缀

需求:

假设数据库表中,记录如下:

 prefix | name | shortname | status 
--------+------+-----------+--------
 abcdef | test | test      | S
 abc    | test | test      | S
 ab     | test | test      | S
 a      | test | test      | S

给定字符串”abcdefghjk”,如何匹配到最长的那条记录?

方案:

在github找到个extension,省去很多麻烦,查看具体信息,请 猛戳这里

测试:

  • 安装
    sudo apt-get install postgresql-9.5-prefix
    psql
    create extension prefix;
  • 数据准备
    create table prefixes (
           prefix    prefix_range primary key,
           name      text not null,
           shortname text,
           status    char default 'S',
    
           check( status in ('S', 'R') )
    );
    insert into prefixes select 'abcdf','test','test','S';
    insert into prefixes select 'abcdef','test','test','S';
    insert into prefixes select 'abc','test','test','S';
    insert into prefixes select 'ab','test','test','S';
    insert into prefixes select 'a','test','test','S';
  • 测试
    test=# select * from prefixes where prefix @> 'abcdefgh' ORDER BY length(prefix) DESC;
     prefix | name | shortname | status 
    --------+------+-----------+--------
     abcdef | test | test      | S
     abc    | test | test      | S
     ab     | test | test      | S
     a      | test | test      | S
    (4 rows)

只要在加上limit 1,即可得到最长的匹配值了。对于数据量大的表还可以建立索引,具体参见github

posted @ 2016-04-07 22:11  cxy486  阅读(3314)  评论(0编辑  收藏  举报