zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    nodeType 节点简介
    Hamming Codes
    Preface Numbering(还没好好看USACO的解答)
    位运算常见应用即ACM题优化实例
    Dynamic Programming(动态规划)
    operator new & new operator
    资料记录
    Ordered Fractions
    Healthy Holsteins
    Sorting A ThreeValued Sequence
  • 原文地址:https://www.cnblogs.com/cxy486/p/5365750.html
Copyright © 2011-2022 走看看